Django test Client submitting a form with a POST request

mmagician picture mmagician · Sep 27, 2017 · Viewed 8.7k times · Source

How can I submit a POST request with Django test Client, such that I include form data in it? In particular, I would like to have something like (inspired by How should I write tests for Forms in Django?):

from django.tests import TestCase

class MyTests(TestCase):
    def test_forms(self):
        response = self.client.post("/my/form/", {'something':'something'})

My endpoint /my/form has some internal logic to deal with 'something'. The problem was that when trying to later access request.POST.get('something') I couldn't get anything. I found a solution so I'm sharing below.

Answer

mmagician picture mmagician · Sep 27, 2017

The key was to add content_type to the post method of client, and also urlencode the data.

from urllib import urlencode

...

data = urlencode({"something": "something"})
response = self.client.post("/my/form/", data, content_type="application/x-www-form-urlencoded")

Hope this helps someone!