Django - Handle JSON request

Oct 23, 2017 Djnago 中文版

In previous post, I’ve showed you how to return JSON-encoded response. Today, let’s continue on dealing with JSON. In this article, I’m going to talk about how to handle JSON requests (POST, PUT, etc.) using Django web framework.


If you have not created a proper environment for the following steps, you can use below commands:

# Install Django
python -m pip install Django

# Check Django's version
python -m django --version

# Create a new Django project
django-admin startproject <project-name>

The structure of your project should look like this:

├── project-name
│   ├──
│   ├──
│   ├──
│   ├──

Handle JSON request

It’s very easy to handle incoming JSON requests using Django. When client side send a JSON request (POST, PUT, etc.), Django will create a HttpRequest object that stores data about the request. And where is our JSON data? You can get it from HttpRequest object’s property body. For example:

import json
from django.views import View

class DummyView(View):

    def post(self, request):

        if request.body:
            # Decode data to a dict object
            json_data = json.loads(request.body)

            # Do things with json_data ...

OK, now you’ve realized how to get JSON data, but it’s quite annoying to add that code snippet into your views again and again, right? In fact, we can utilize Decorator to take over repetitive work.

Use Decorator

Using Decorator allows us to reduce redundant code snippets easily, and Django already provides us with a useful utility called django.utils.decorators. Let me show you how to use it. First, create a Python script named, and then put below contents into it:

import json
from functools import wraps
from django.conf import settings
from django.http import HttpRequest, HttpResponse

def dummy_json(view_func):

    def wrapper_view_func(request, *args, **kwargs):

        # Add simple validation or your own validation rule
        if request.content_type == 'application/json':
            if request.body:
                # Decode data to a dict object
                request.json = json.loads(request.body)
                request.json = None
        return view_func(request, *args, **kwargs)
    return wrapper_view_func

As you see, I defined a decorator named dummy_json, and we can apply it in like this:

import json
from decorators import *
from django.views import View
from django.utils.decorators import method_decorator

class DummyView(View):

    def post(self, request):
        json_data = request.json

        # Then do things with json_data ...

Now, you can start to handle JSON requests with custom decorator.

You might also like:

If you have any suggestions, questions or even find some typos, feel free to contact me. Thank you! :)   © 2015-2019 zeckli, thanks to Jekyll and GitHub.