Search code examples
django-rest-frameworkdjango-rest-viewsets

Access current user from viewsets.ViewSet


I am trying to access current user from List method in viewsets.ViewSet. But I am getting AnonymousUser.

I have tried this

class ReportViewSet(viewsets.ViewSet):
    """Shows purchase report group by day"""

    def list(self, request, **kwargs):
        print(self.request.user)

Is there any way to access current user from viewsets.ViewSet?


Solution

  • Solved

    from rest_framework.authentication import TokenAuthentication
    
    class ReportViewSet(viewsets.ViewSet):
        """Shows purchase report group by day"""
    
        authentication_classes = (TokenAuthentication,)
    
    
        def list(self, request, **kwargs):
            print(self.request.user)