Fix Python – How should I write tests for Forms in Django?


Asked By – Mridang Agarwalla

I’d like to simulate requests to my views in Django when I’m writing tests. This is mainly to test the forms. Here’s a snippet of a simple test request:

from django.tests import TestCase

class MyTests(TestCase):
    def test_forms(self):
        response ="/my/form/", {'something':'something'})
        self.assertEqual(response.status_code, 200) # we get our page back with an error

The page always returns a response of 200 whether there’s an form error or not. How can I check that my Form failed and that the particular field (soemthing) had an error?

Now we will see solution for issue: How should I write tests for Forms in Django?


I think if you just want to test the form, then you should just test the form and not the view where the form is rendered. Example to get an idea:

from django.test import TestCase
from myapp.forms import MyForm

class MyTests(TestCase):
    def test_forms(self):
        form_data = {'something': 'something'}
        form = MyForm(data=form_data)
        ... # other tests relating forms, for example checking the form data

This question is answered By – Torsten Engelbrecht

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0