问题
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