Reputation: 786
I'm trying to create a form consisting of a multiple select field which is used to select multiple instances of my Person model.
class MyForm(forms.Form):
choices = [(p.id, str(p)) for p in Person.objects.all()]
my_field = forms.ChoiceField(widget=forms.SelectMultiple, choices=choices)
The widget looks exactly like I want, but when I submit the form, it fails with the message
Select a valid choice. ['2', '3'] is not one of the available choices.
What am I doing wrong? When removing the widget=forms.SelectMultiple,
from the third line, it works, but then it's only a single select field.
Upvotes: 1
Views: 1012
Reputation: 308879
You are getting the error because ChoiceField
expects a single choice.
If you want to allow multiple choices, use a MultipleChoiceField
.
my_field = forms.MultipleChoiceField(choices=choices)
Note you don't have to specify the widget, as it's forms.SelectMultiple
by default.
Upvotes: 3