如何基于复选框输入启用Django表单字段?

时间:2018-08-20 14:34:27

标签: javascript python django django-forms

这是我的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())

我必须基于字段“功能”(MultipleChoiceField)启用所有字段。根据选择,我必须启用“选择”字段。 我该怎么办,谢谢。

1 个答案:

答案 0 :(得分:0)

不确定要查找的内容是什么,但是如果需要将动态选择输入模型的能力,

models.py

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/