如何根据复选框输入启用django表单字段?

问题描述 投票:0回答:1

这是我的django动态表单,它根据给定的csv文件列生成字段。

 class SetFeatureForm(forms.Form):

    def __init__(self, project=None, *args, **kwargs):

        super(SetFeatureForm, self).__init__(*args, **kwargs)
        if project:
            choices = [(column,column) for column in pd.read_csv(project.file.path).columns]
            self.fields['feature'] = forms.MultipleChoiceField(choices=choices, required=True, )
            self.fields['feature'].widget.attrs['size']=len(choices)
            for _,choice  in choices:
                self.fields[choice] = forms.ChoiceField( choices=DATA_TYPE.items())

我必须根据字段'feature'启用所有字段,即MultipleChoiceField。根据选择,我必须启用“选择”字段。我怎么能这样做,提前谢谢。

javascript python django django-forms
1个回答
0
投票

不确定您正在寻找什么,但如果您需要能够在模型中输入动态选项:

models.朋友

def get_menu_choices():
    choices_tuple = []
    #do your stuff
    return choices_tuple

class ChoiceModel(models.Model):
    choices_f = models.CharField(max_length=8, blank=True)

    def __init__(self,  *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._meta.get_field('choices_f')._choices = lazy(get_menu_choices, list)()

    def get_absolute_url(self):
        return reverse('testapp:choicemodel_list')

否则,如果您已经知道标题并且它们是静态的,您可以关注https://docs.djangoproject.com/en/2.1/ref/models/fields/#choices

只需确保将表单修改为:forms.py

class ChoiceForm(forms.ModelForm):
    class Meta():
        model = ChoiceModel
        fields = ['choices_f']

顺便说一下上面的动态解决方案来自http://blog.yawd.eu/2011/allow-lazy-dynamic-choices-djangos-model-fields/

© www.soinside.com 2019 - 2024. All rights reserved.