81

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?

Alok
  • 7,734
  • 8
  • 55
  • 100
  • Possible duplicate of [Where's my JSON data in my incoming Django request?](http://stackoverflow.com/questions/1208067/wheres-my-json-data-in-my-incoming-django-request) – e4c5 May 16 '17 at 10:21

3 Answers3

149

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)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 24
    request.body contains bytestring, whereas python3 json.loads expects a str thus you should decode first: `data = request.body.decode('utf-8') received_json_data = json.loads(data)` – stelios Feb 18 '17 at 14:57
  • 1
    But it said he tried `request.body`, how come it works for him now? I used `request.body` and it didn't work. – AnonymousUser Aug 02 '21 at 08:41
85

For python3 you have to decode body first:

received_json_data = json.loads(request.body.decode("utf-8"))
Thran
  • 1,111
  • 8
  • 10
-4

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

Kracekumar
  • 19,457
  • 10
  • 47
  • 56