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


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 is

import json
from django.http import StreamingHttpResponse
def main_page(request):
    if request.method=='POST':
            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'}, data=json.dumps(data), headers=headers)

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?

6/5/2014 7:25:31 PM

Accepted Answer

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.

6/9/2014 12:02:08 PM

For python3 you have to decode body first:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow