How to receive json data using HTTP POST request in Django 1.6?

PythonDjangoDjango ViewsHttp PostPython Requests

Python Problem Overview


I am learning Django 1.6.
I want to post some JSON using HTTP POST request and I am using Django for this task for learning.
I tried to use request.POST['data'], request.raw_post_data, request.body but none are working for me.
my views.py is

import json
from django.http import StreamingHttpResponse
def main_page(request):
    if request.method=='POST':
            received_json_data=json.loads(request.POST['data'])
            #received_json_data=json.loads(request.body)
            return StreamingHttpResponse('it was post request: '+str(received_json_data))
    return StreamingHttpResponse('it was GET request')

I am posting JSON data using requests module.

import requests  
import json
url = "http://localhost:8000"
data = {'data':[{'key1':'val1'}, {'key2':'val2'}]}
headers = {'content-type': 'application/json'}
r=requests.post(url, data=json.dumps(data), headers=headers)
r.text

r.text should print that message and posted data but I am not able to solve this simple problem. please tell me how to collect posted data in Django 1.6?

Python Solutions


Solution 1 - Python

You're confusing form-encoded and JSON data here. request.POST['foo'] is for form-encoded data. You are posting raw JSON, so you should use request.body.

received_json_data=json.loads(request.body)

Solution 2 - Python

For python3 you have to decode body first:

received_json_data = json.loads(request.body.decode("utf-8"))

Solution 3 - Python

Create a form with data as field of type CharField or TextField and validate the passed data. Similar SO Question

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlokView Question on Stackoverflow
Solution 1 - PythonDaniel RosemanView Answer on Stackoverflow
Solution 2 - PythonThranView Answer on Stackoverflow
Solution 3 - PythonKracekumarView Answer on Stackoverflow