Pass request.user to dispatch method in Django Rest Framework

Submitted 3 years, 7 months ago
Ticket #119
Views 816
Language/Framework Django
Priority Medium
Status Closed

Environment: Python 3.6, Django 3.0, DRF 3.11, JWT Authorization

I have a simple class in my API where I want to check user permissions in each method getpass etc. I planned to check user privileges at dispatch but it doesn't work. Simplify code, my current class looks more or less like this:

class ExampleClassName(APIView):
    can_do_sth = False

    def dispatch(self, request, *args, **kwargs):
        print(request.user)  # Here is AnonymousUser
        if request.user.username == "someuser":
            self.can_do_sth = True
        return super(ExampleClassName, self).dispatch(request, *args, **kwargs)

    def get(self, request):
        print(request.user)  # Here is correctly Logged user
        if self.can_do_sth:
            return Response("sfdgsdfgdfs")
        return Response("dfgfdsg")

    def post(self, request):
        print(request.user)  # Here is correctly Logged user
        if self.can_do_sth:
            return Response("dfgfdg")
        return Response("dfgsdfg")

How can I pass request.user to dispatch method?

Submitted on Sep 08, 20
add a comment

1 Answer

Verified

We could use method .initialize_request(self, request, *args, **kwargs)

def dispatch(self, request, *args, **kwargs):
    req = self.initialize_request(request, *args, **kwargs)
    if req.user.username == "someuser":
        self.can_do_sth = True
    return super(ExampleClassName, self).dispatch(request, *args, **kwargs)

Check this if it helps.

Submitted 3 years, 7 months ago


Latest Blogs