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

MultipleChoiceFileld in ModelForm will only submit when default option available but nothing is selected

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

有两个链接?问题:

如果有人能告诉我哪里出了问题,将不胜感激。

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,}

问题是您在表单中使用了 MultipleChoiceField,但在模型中使用了 CharFieldCharField 存储字符串,而不是列表,因此您的模型期望来自选择列表的 单个 (字符串)值,而不是您的 CheckboxSelectMultiple 回来了。

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

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