在从 Django 2.2 中的动态元组列表生成的 MultipleChoiceField 中选择多个选项

时间:2021-02-01 12:45:54

标签: django django-forms multiplechoicefield

我有一个从过滤的元组列表动态生成的 MultipleChoiceField,dynamic_ls,我希望能够选择或选择多个选项。下面的表单域只适用于选择一个选项,如何将其更改为选择多个选项?

例如,只能在从列表 dynamic_ls =[('A'),('B' ),('C')] 在“选项”字段中,当我希望能够选择多个或所有选项 ('A')、('B') 和/或 ('C')。< /p>

 # in forms.py
 
 class Form1(forms.ModelForm):
   class Meta:
     model = ModelA
     fields = ('title',)

   def __init__(self, *args, **kwargs):
       self.dynamic_ls = kwargs.pop('dynamic_ls', None)
       super(Form1, self).__init__(*args, **kwargs)

     # It's only possible to select one choice with this widget and with this formulation when I want to select multiple choices

       self.fields['options'] = forms.MultipleChoiceField(
            widget=forms.SelectMultiple(
                    attrs={'class': 'form-control'}
            ),
            choices=[(o, str(o)) for o in self.dynamic_ls],
            required=False
     )

    def clean(self):
        cleaned_data = super(Form1, self).clean()
        return cleaned_data

0 个答案:

没有答案