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 get
, pass
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?
We could use method .initialize_request(self, request, *args, **kwargs)
Check this if it helps.