Django:如何在表单/ admin中使用MultipleChoiceField

时间:2017-07-17 20:48:30

标签: python django

我需要一个MultipleChoiceField和在线注册应用程序。当我尝试在一个字段中使用它时,我得到一个未知的字段错误。它们也不会出现在管理面板中。

# models.py
...
CHILDCARE_REASONS = (('Working', 'working'),('Training', 'training'),('Teen Parent', 'teen_parent'),('Working W/Child With A Disability', 'child_disability'),('Adult W/Disability', 'adult_disability'),)
reasons_for_childcare = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=CHILDCARE_REASONS)
...

# forms.py
class EnrollForm(forms.ModelForm):
class Meta:
    model = EnrollmentApplication
    fields = [
        ...
        'reasons_for_childcare ',
        ...
    ]

1 个答案:

答案 0 :(得分:2)

  1. 不要在模型中使用表单字段,这是不对的。对于多选字段,我建议使用django-multiselectfield

  2. 您需要更改元组顺序,首先是正确的方法,然后是值。

  3. 字段字符串“reason_for_childcare”的末尾有一个额外的空格。

  4. 因此,考虑到这一点,解决方案将如下所示:

    <强> models.py

    Apple

    <强> forms.py

    from multiselectfield import MultiSelectField
    
    
    class EnrollmentApplication(models.Model):
        CHILDCARE_REASONS = (('working', 'Working'),
                             ('training', 'Training'),
                             ('teen_parent', 'Teen Parent'),
                             ('child_disability', 'Working W/Child With A Disability'),
                             ('adult_disability', 'Adult W/Disability'))
        reasons_for_childcare = MultiSelectField(choices=CHILDCARE_REASONS)