In the django documentation, it says:
HttpRequest.POST
A dictionary-like object containing all given HTTP POST parameters, providing that the request contains form data. See the QueryDict documentation below. If you need to access raw or non-form data posted in the request, access this through the HttpRequest.body attribute instead.
However, the server does not respond to a browser (such as using JS frameworks or a form) but instead a REST api sent by an Anroid/iOS application.
If the client sends fields directly in a POST request, how can I read the data? For example, this (Java + Unirest):
Unirest.post("/path/to/server")
.field("field1", "value2")
.field("field2", "value2");
EDIT: Can I simply read the data usingresponse.POST["field1"]
, or will I have to do something with request.body
?
EDIT 2: So I can simply use request.body
as a dictionary-like object similar to request.POST
?
As far as I understand the field method from Unirest just uses normal application/x-www-form-urlencoded
data like a HTML form. So you should be able to just use response.POST["field1"]
like you suggested.
From the docs:
request.data
returns the parsed content of the request body. This is similar to the standardrequest.POST
andrequest.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 ofPUT
andPATCH
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.
Can I simply read the data using
response.POST["field1"]
, or will I have to do something withrequest.body
?So I can simply use
request.body
as a dictionary-like object similar torequest.POST
?
An example - From a create
method (viewsets):
user = dict(
full_name=request.DATA['full_name'],
password=request.DATA['password'],
email=request.DATA['email'],
personal_number=request.DATA['personal_number'],
user_type=request.DATA['user_type'],
profile_id=request.DATA['profile_id'],
account_id=request.DATA['account_id']
)
Edit 1: In version 3 (latest) - request.DATA
has been replaced with request.data
:
user = dict(
full_name=request.data['full_name'],
password=request.data['password'],
email=request.data['email'],
personal_number=request.data['personal_number'],
user_type=request.data['user_type'],
profile_id=request.data['profile_id'],
account_id=request.data['account_id']
)
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