CheckboxSelectMultiple validation error when submitting the form on Django

纵饮孤独 提交于 2019-12-25 08:27:33

问题


models.py

class MyModel(models.Model):
      OPTION_CHOICES = (('a','a'),('b','b'))
      option = models.CharField(max_length=1, choices=OPTION_CHOICES)

forms.py

class MyForm(ModelForm):
      class Meta:
            model=MyModel
            fields=['option']
            widgets = {'option':CheckboxSelectMultiple(),}

When I try to submit the form, I have validation error and can't submit it. When I chance CheckboxSelectMultiple to RadioSelect it works just fine. So how can I fix this using checkboxSelectMultiple


回答1:


option = models.CharField(max_length=1, choices=OPTION_CHOICES)

Only accepts a single char. By submitting the form with multiple choice widget you try to store a list:

[u'a']

This of course will result in an error:

Select a valid choice. [u'a'] is not one of the available choices.

Again: 'a' or 'b' are strings and valid choices, [u'a'] is a list an is not valid.

To store lists (or multiple relations) you should pick some other field type. What field type exactly depends on your project requirements. There is not enough info to give you advice what to use.



来源:https://stackoverflow.com/questions/41558414/checkboxselectmultiple-validation-error-when-submitting-the-form-on-django

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