Reputation: 368
I have a form
class TypesForm(forms.Form):
....
types = forms.ModelChoiceField(
label='Types',
queryset=models.Type.objects.all(),
widget=forms.CheckboxSelectMultiple)
...
How do I write a unit test for this form, when I want to test multiple boxes selected?
For one field check works following:
form = forms.TypesForm({'types': 1})
self.assertTrue(form.is_valid())
But anything I tried to set two selected checkboxes, it results in errors:
{'types': [u'Select a valid choice. That choice is not one of the available choices.']}
I tried, but these does not work. E.g. :
form = forms.TypesForm({'types': [1, 2]})
form = forms.TypesForm({'types': (1, 2)})
and other options..
For forms.ModelForm the list [1, 2] works, so there needs to be a way.
Upvotes: 3
Views: 1072
Reputation: 309049
The ModelChoiceField
allows you to select a single object. If you want to allow multiple objects to be selected, use a ModelMultipleChoiceField
.
In your unit test, pass a list of ids for the field, for example:
form = forms.TypesForm({'types': [1, 2]})
Upvotes: 2