首页 > 解决方案 > 如何根据复选框输入启用 django 表单字段?

问题描述

这是我的 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。根据选择,我必须启用“选择”字段。我该怎么做,提前谢谢。

标签: javascriptpythondjangodjango-forms

解决方案


不确定您正在寻找什么,但如果您需要将动态选择输入模型的能力:

模型.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/


推荐阅读