[Fixed]-Acessing POST field data without a form (REST api) using Django

8👍

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.

6👍

From the docs:

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.

Can I simply read the data using response.POST["field1"], or will I
have to do something with request.body?

So I can simply use request.body as a dictionary-like object similar
to request.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']
                )

6👍

If the api you are interacting with is a sipmle Django Class Based view, you access the data through request.body something like this:

class MyView(View):
    def post(self, request):
        field1 = request.body.get('field1')
        field2 = request.body.get('field2')
        ... # processing here

In case you are using Django rest framework api, you access the data through request.data:

field1 = request.data.get('field1')
field2 = request.data.get('field2')

NB: If you find request.DATA used somewhere in Internet that’s correct too, but it’s only valid for old version of DRF, and it’s deprecated in favor of request.data in the newer versions.

👤Dhia

Leave a comment