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.
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!
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With