Alok
Alok

Reputation: 10618

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

I want to post some JSON using HTTP POST request and receive this data in Django.
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?

Upvotes: 87

Views: 125995

Answers (4)

Ryan
Ryan

Reputation: 1235

HttpRequest is a file-like object so you can simplify from json.loads(request.body) slightly:

data = json.load(request)

Upvotes: 0

Thran
Thran

Reputation: 1140

For python3 you have to decode body first:

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

Upvotes: 87

Daniel Roseman
Daniel Roseman

Reputation: 599926

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)

Upvotes: 155

Kracekumar
Kracekumar

Reputation: 20419

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

Upvotes: -4

Related Questions