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?
Using Form in a View In Django, the request object passed as parameter to your view has an attribute called "method" where the type of the request is set, and all data passed via POST can be accessed via the request. POST dictionary. The view will display the result of the login form posted through the loggedin.
To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.
POST requestsIn Postman, change the method next to the URL to 'POST', and under the 'Body' tab choose the 'raw' radio button and then 'JSON (application/json)' from the drop down. You can now type in the JSON you want to send along with the POST request. If this is successful, you should see the new data in your 'db.
Django pass POST data to view The input fields defined inside the form pass the data to the redirected URL. You can define this URL in the urls.py file. In this URLs file, you can define the function created inside the view and access the POST data as explained in the above method. You just have to use the HTTPRequest.
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)
For python3 you have to decode body first:
received_json_data = json.loads(request.body.decode("utf-8"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With