form with CheckboxSelectMultiple doesn't validate

混江龙づ霸主 提交于 2019-12-20 17:32:17

问题


I have a form with a choice field that is using CheckboxSelectMultiple widget:

foo = forms.ChoiceField(widget=forms.CheckboxSelectMultiple,
                        choices=(
                                  ("1", "ONE"),
                                  ("2", "TWO"),
                                 ))

The form renders fine showing two checkboxes, however it doesn't validate.

If I select both checkboxes I am getting an error: Select a valid choice. [u'1', u'2'] is not one of the available choices

Selecting one checkbox doesn't work either, it gives me: Select a valid choice. [u'1'] is not one of the available choices.

What's going on here?


回答1:


If you make the field a forms.MultipleChoiceField rather than a forms.ChoiceField it will work better.




回答2:


May this helpful for you

num_choices = ( ("1", "ONE"), ("2", "TWO"), ("3", "Three"), ("4", "Four"))

num_list = forms.MultipleChoiceField(choices=num_choices, required=True, widget=forms.CheckboxSelectMultiple(), label='Select No', initial=("1", "2"))

If you want to pass the ORM object directly, then you can try the following

num_list = forms.ModelMultipleChoiceField(Numbers.objects.all(), required=True, widget=forms.CheckboxSelectMultiple(), label='Select No')


来源:https://stackoverflow.com/questions/746173/form-with-checkboxselectmultiple-doesnt-validate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!