So I present a checkbox to the user, as you can see inside my forms.py file:
class AddFooToBarForm(forms.Form):
to_original = forms.BooleanField(initial=True,
error_messages={'required':
"Oh no! How do I fix?"})
...
Depending on whether the user checks or unchecks that checkbox, I do something different, as you can see inside my views.py file:
def add_foo_to_bar(request, id):
...
try:
bar = Bar.objects.get(pk=id)
if request.method == 'POST': # handle submitted data
form = AddFooToBarForm(bar, request.POST)
if form.is_valid(): # good, now create Foo and add to bar
...
to_original = form.cleaned_data['to_original']
print 'to original is {0}'.format(to_original) # for debugging
if to_original:
# do A
else:
# do B
...
So I want to test that my site does indeed perform the correct actions, depending on whether the user checks the checkbox or not, inside my tests.py file:
class FooTest(TestCase):
...
def test_submit_add_to_Bar(self):
form_data = {
...
'to_original': True,
}
response = self.client.post(reverse('add_foo_to_bar', args=(self.bar.id,)),
form_data, follow=True)
self.assertContains(...) # works
...
form_data['to_original'] = None
response = self.client.post(reverse('add_foo_to_bar', args=(self.bar.id,)),
form_data, follow=True)
print response # for debugging purposes
self.assertContains(...) # doesn't work
I’ve tried
del form_data['to_original']— this gives me the “Oh no! How do I fix?” error messageform_data['to_original'] = None— in my view function, I getTrue, so A is done instead of Bform_data['to_original'] = False— this gives me the “Oh no! How do I fix?” error message once again
So how should I test the user not checking the checkbox in Django? (I’m using the latest version, 1.4.3)
When checkbox is not checked, its not present in submitted form. Also, when submitted value is
'on'.If you want to make
BooleanFieldoptional haverequired=Falsewhile defining the form field.Documentation BooleanField.