Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest frameworks: request.Post vs request.data?

Tags:

The Django Rest Frameworks has this to say about POST, quoting a Django dev

Requests

If you're doing REST-based web service stuff ... you should ignore request.POST.

— Malcom Tredinnick, Django developers group

As not-so experienced web-developer, why is request.POST (standard) discouraged over request.DATA (non-standard)? Is one more flexible?

like image 415
AncientSwordRage Avatar asked Feb 16 '15 16:02

AncientSwordRage


People also ask

What is request data in Django?

Django REST framework introduces a Request object that extends the regular HttpRequest, this new object type has request. data to access JSON data for 'POST', 'PUT' and 'PATCH' requests. However, I can get the same data by accessing request. body parameter which was part of original Django HttpRequest type object.

What is request post in Django?

request. POST is an attribute of this request object, it's a QueryDict (much similar to a normal Python dict). It contains the HTTP POST parameters that are sent to your view.

What are request get and request post objects in Django?

In an HttpRequest object, the GET and POST attributes are instances of django.http.QueryDict , a dictionary-like class customized to deal with multiple values for the same key. This is necessary because some HTML form elements, notably <select multiple> , pass multiple values for the same key.

How do you pass extra context data to Serializers in Django REST framework?

In function based views we can pass extra context to serializer with "context" parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with "self. context". From example, to get "exclude_email_list" we just used code 'exclude_email_list = self.


1 Answers

The docs cover this:

request.data returns the parsed content of the request body. This is similar to the standard request.POST and request.FILES attributes except that:

  • It includes all parsed content, including file and non-file inputs.
  • It supports parsing the content of HTTP methods other than POST, meaning that you can access the content of PUT and PATCH requests.
  • It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming JSON data in the same way that you handle incoming form data.

The last two are the important ones. By using request.data throughout instead of request.POST, you're supporting both JSON and Form-encoded inputs (or whatever set of parsers you have configured), and you'll be accepting request content on PUT and PATCH requests, as well as for POST.

Is one more flexible?

Yes. request.data is more flexible.

like image 143
Tom Christie Avatar answered Sep 19 '22 21:09

Tom Christie