Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to parse `request.body` from POST in Django [duplicate]

For some reason I cannot figure out why Django isn't handling my request.body content correctly.

It is being sent in JSON format, and looking at the Network tab in Dev Tools shows this as the request payload:

{creator: "creatorname", content: "postcontent", date: "04/21/2015"} 

which is exactly how I want it to be sent to my API.

In Django I have a view that accepts this request as a parameter and just for my testing purposes, should print request.body["content"] to the console.

Of course, nothing is being printed out, but when I print request.body I get this:

b'{"creator":"creatorname","content":"postcontent","date":"04/21/2015"}' 

so I know that I do have a body being sent.

I've tried using json = json.loads(request.body) to no avail either. Printing json after setting that variable also returns nothing.

like image 690
Zach Avatar asked Apr 21 '15 18:04

Zach


People also ask

What is request method == POST in Django?

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 can I get post request in Django?

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.

How does Django get JSON data?

To receive JSON data using HTTP POST request in Python Django, we can use the request. body property in our view. to call json. oads with request.

What kind of data is passed into a view in the request object Django?

Django uses request and response objects to pass state through the system. 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.


1 Answers

In Python 3.0 to Python 3.5.x, json.loads() will only accept a unicode string, so you must decode request.body (which is a byte string) before passing it to json.loads().

body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) content = body['content'] 

In Python 3.6, json.loads() accepts bytes or bytearrays. Therefore you shouldn't need to decode request.body (assuming it's encoded in UTF-8, UTF-16 or UTF-32).

like image 162
Alasdair Avatar answered Oct 05 '22 23:10

Alasdair