Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django rest framework request vs self.request

in djnago rest framework what is difference between self.request and request in why we cant always use request and exactly in what situations we need to use self.request or request

class MyView(APIView):

    def post(self, request, format=None):
        data = self.request.data
        login(request, user)

i try to print them and both of them return same thing

<rest_framework.request.Request: POST '/url/sub_url'>

so why we user like

data = self.request.data
login(request, user)
like image 357
hamzeh_pm Avatar asked Aug 06 '26 02:08

hamzeh_pm


2 Answers

the request argument is passed to the post method. like any normal function that you can define and use its arguments.

But since post is a method it takes self argument. you can access the class methods and attributes including request.

And they're the same.

When request is passed to your function just use request but if not and you need request use self.request.

like image 128
Mojtaba Arezoomand Avatar answered Aug 07 '26 17:08

Mojtaba Arezoomand


If you are using function based views, you wont be able to use self.request. Here as you are using class based views, you can access it both ways.

like image 36
Muhammad Hassan Avatar answered Aug 07 '26 19:08

Muhammad Hassan