Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django POST data in request.body but can not store in variable

Tags:

I am posting some raw JSON to my backend

{
    "access_token": "hU5C7so4reJOYTzPyhKPs8PWq07tb",
    "id": 3,
    "order_details": [{"meal_id": 1, "quantity": 3}, {"meal_id": 2, "quantity": 2}]
}

However when I try to

print (request.POST.get("access_token")) 

I receive None

But, when I do

print (request.body)

The values seem to there: b'{\n\t"access_token": "hU5C7so4reJOYTzPyhKPs8PWq07tb",\n\t"id": 3,\n\t",\n\t"order_details": [{"meal_id": 1, "quantity": 3}, {"meal_id": 2, "quantity": 2}]\n}'

I am using Postman to post the data.

I want to store the access token into some variable like so:

access_token = request.POST.get("access_token")

with the post data

I am still fairly new to Django, any help would be great.

like image 206
Simon Avatar asked Apr 03 '17 06:04

Simon


People also ask

What is request method == POST in Django?

The result of request. method == "POST" is a boolean value - True if the current request from a user was performed using the HTTP "POST" method, of False otherwise (usually that means HTTP "GET", but there are also other methods).

How does Django read POST data?

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.

What is HttpRequest in Django?

When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function. Each view is responsible for returning an HttpResponse object.


2 Answers

Request.POST gets populated when you are sending form data. see django doc, and this answer for details. Since, in your case, you are posting 'plain' json, you will find your payload under request.body. You can decode the body from binary to a dict as follows:

import json

body = json.loads(request.body.decode('utf-8'))
access_token = body.get("access_token")
like image 115
Fred Avatar answered Sep 24 '22 11:09

Fred


Just doing a json.loads should work.

import json

json_data = json.loads(request.body)
like image 33
SuperNova Avatar answered Sep 22 '22 11:09

SuperNova