Blog

Django: How to send request to JSON view in tests

VM Vera Mazhuga Vera Mazhuga

Vera Mazhuga

Software Developer
1 min read.

If in your Django project you have a view that accepts or returns JSON, you can use the following code for your unittests

import json
from django.test import TestCase

class JSONViewTestCase(TestCase):
    def test_json_view(self):
        response = self.client.post(
            reverse(
                'my_json_view',
                args=('test', 123)
            ),
            json.dumps({
                'user': 'me@example.com',
            }),
            'json',
            HTTP_X_REQUESTED_WITH='XMLHttpRequest',
        )
        json_string = response.content
        response_data = json.loads(json_string)
        # do smth.

Written by Vera Mazhuga

VM Vera Mazhuga Vera Mazhuga

Vera specializes in writing and maintaining code for various applications. Her focus on problem-solving and efficient programming ensures reliable and effective software solutions.

Scale your company with the same people

Practical ideas to do more and get back your time every week

We respect your inbox. Privacy policy

Wait. There's more:

Atom editor for Debian

When Github announced that they made an editor and at the office and Pablo brought it for the first time in its invitation pe...

1 min read.

Simple jquery image lazy load

Sometimes you want to speed up the loading time of a web page, when you have a lot of images it can be useful to load them a...

1 min read.

Build to
Inspire