Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access get request data in django rest framework

How to access GET request data in django rest framework. In the docs, they have mentioned "For clarity inside your code, we recommend using request.query_params instead of the Django's standard request.GET"

https://www.django-rest-framework.org/api-guide/requests/

But when I use request.query_params.get('some_vaue') it gives me none even though I pass the data in the request body.

sample code example:

class TestView(APIView):
    def get(self, request):
        test = request.query_params.get('test')
        print('data',test)
        ...
        ...
        ...

When I pass some value in the body of the request in postman and print the value, it actually prints None.

Update

Below is my axios code

 axios.get(API_URL, {
            headers: {
                'Content-Type': 'application/json'
            },
            params: {
                page_num: 1, 
                test: 'test data'
            }
        })
        .then(res => {
            console.log(res);
        })
        .catch(err => {
            console.log(err.response.data);
        });

Re-Update:

For testing purpose I printed out the request object like

print(request.__dict__)

so it printed out

{'_request': <WSGIRequest: GET '/api/my api url/?page_num=1&test=test+data'>, 'parsers': [<rest_framework.parsers.JSONParser object at 0x0000016742098128>, <rest_framework.parsers.FormParser object at 0x00000167420980B8>, <rest_framework.parsers.MultiPartParser object at 0x00000167420980F0>], 'authenticators': (), 'negotiator': <rest_framework.negotiation.DefaultContentNegotiation object at 0x0000016742098080>, 'parser_context': {'view': <app_name.views.APIClassName object at 0x0000016742280400>, 'args': (), 'kwargs': {}, 'request': <rest_framework.request.Request object at 0x0000016742107080>, 'encoding': 'utf-8'}, '_data': {}, '_files': <MultiValueDict: {}>, '_full_data': {}, '_content_type': <class 'rest_framework.request.Empty'>, '_stream': None, 'accepted_renderer': <rest_framework.renderers.JSONRenderer object at 0x00000167421070B8>, 'accepted_media_type': 'application/json', 'version': None, 'versioning_scheme': None, '_authenticator': None, '_user': <django.contrib.auth.models.AnonymousUser object at 0x0000016741FFAC88>, '_auth': None}

I could see that it is passing the data but not sure why if i do request.data['page_num'] or any other value it doesn't get the data.

like image 489
Aashay Amballi Avatar asked Oct 02 '19 18:10

Aashay Amballi


People also ask

How do I get data from Django REST framework?

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.

How do I see requests in Django?

From Django Docs. Request came from User that want to load page. 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.

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.


1 Answers

If you are using class based views :

POST provides data in request.data and GET in request.query_params

If you are using function based views:

request.data will do the work for both methods.

axios does not support sending params as body with get method , it will append params in url. so if you are using axios you will have to use query_params

Axios example code:

axios.get(API_URL, {
            params: {
                testData: 'test data',
                pageNum: 1
            }
        })
        .then(res => {
            console.log(res);
        })
        .catch(err => {
            console.log(err.response.data);
        });

DRF example code:

Class TestView(APIView):
    def get(self, request):
        test_data_var = request.query_params['testData']
        page_num_var = request.query_params['pageNum']

Note: If you're testing it in postman then put the get request query params in Params tab.

like image 173
Naveen Jain Avatar answered Sep 28 '22 10:09

Naveen Jain