Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django test Client submitting a form with a POST request

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.

like image 360
mmagician Avatar asked Sep 27 '17 13:09

mmagician


2 Answers

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!

like image 96
mmagician Avatar answered Nov 14 '22 20:11

mmagician


If you are sending dictionaries on old-django versions using client you must define content_type='application/json' because its internal transformation fail to process dictionaries, also need send dictionary like a blob using json.dumps method, in conclusiont the next must works

import json
from django.tests import TestCase

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

like image 2
jaime negrete Avatar answered Nov 14 '22 21:11

jaime negrete