我正在尝试将MultipleChoiceField
与ModelForm一起使用,但显然是错误的。
有两个链接?的问题:
blank=True
删除“-----”,则根本无法提交问题,请参阅下面的图片。
如果有人能告诉我自己出了什么问题,那将会非常受欢迎。
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,}
答案 0 :(得分:1)
问题是您在表单中使用MultipleChoiceField
,但模型中有CharField
。 CharField
存储字符串,而不是列表,因此您的模型期望选项列表中的单个(字符串)值,而不是[u'LOCAL', u'NATIONAL', u'PRESIDENTIAL']
列表CheckboxSelectMultiple
正在回来。
您可以将elections
设为ManyToMany
字段,从而在单个字段elections
中存储多个值。
或查看this question以获得进一步说明。