ModelForm中的MultipleChoiceFileld仅在默认选项可用时提交但未选择任何内容

时间:2015-05-13 19:14:56

标签: django django-models django-forms

我正在尝试将MultipleChoiceField与ModelForm一起使用,但显然是错误的。

有两个链接?的问题:

  • 只提交用户的问题
  • 问题显示我要删除的默认选项“------”
    • 如果我删除blank=True删除“-----”,则根本无法提交问题,请参阅下面的图片。

enter image description here

如果有人能告诉我自己出了什么问题,那将会非常受欢迎。

modles.py

ELECTIONS = (
    ('NONE', 'None'),
    ('LOCAL', 'Local elections'),
    ('STATE', 'State elections e.g. Governorship'),
    ('NATIONAL', 'National elections e.g. Congress and Senate'),
    ('PRESIDENTIAL', 'Presidential elections'),
    ('OTHER', 'Other'),
    ('DONT_KNOW', "Don't know"),
    )

elections = models.CharField(null=True, max_length=100, blank=True, default=None, choices = ELECTIONS, verbose_name = 'Which elections do you regularly vote in or intend to vote in? Select all that apply.')

forms.py

class SurveyFormD(forms.ModelForm): # Political Viewpoints

    class Meta:
        model = Person
        fields = ['liberal_conservative', 'democrat_republican', 'voting_rights', 'elections']        

        widgets = {'liberal_conservative' : forms.RadioSelect,
                   'democrat_republican' : forms.RadioSelect,
                   'voting_rights' : forms.RadioSelect,
                   'elections' : forms.CheckboxSelectMultiple,}

1 个答案:

答案 0 :(得分:1)

问题是您在表单中使用MultipleChoiceField,但模型中有CharFieldCharField存储字符串,而不是列表,因此您的模型期望选项列表中的单个(字符串)值,而不是[u'LOCAL', u'NATIONAL', u'PRESIDENTIAL']列表CheckboxSelectMultiple正在回来。

您可以将elections设为ManyToMany字段,从而在单个字段elections中存储多个值。

或查看this question以获得进一步说明。