pythondjangodjango-rest-frameworkdjango-viewsets

How to get the authentication information in ModelViewSet?


I am using rest framework with ModelViewSet

class DrawingViewSet(viewsets.ModelViewSet):
    queryset = m.Drawing.objects.all()
    serializer_class = s.DrawingSerializer
    filterset_fields = ['user']
    def list(self, request):
        queryset = m.Drawing.objects.all()
        serializer = s.DrawingSerializer(queryset, many=True)
        
        return Response(serializer.data)

With this script, I can use filter such as /?user=1

Howver this user=1 is not necesary when authentication information is used in script. (Because one user needs to fetch only data belonging to him/herself)

How can I get the authentication data in list?


Solution

  • If you want to return data based on user him/herself, there is no need to pass user id. If your user is authenticated, you can have his/her ID via request so:

    from rest_framework.permissions import IsAuthenticated
    
    
    class DrawingViewSet(viewsets.ModelViewSet):
        ...
        permission_classes = (IsAuthenticated,)
        def list(self, request):
            queryset = m.Drawing.objects.filter(user=request.user)
            serializer = s.DrawingSerializer(queryset, many=True)
            
            return Response(serializer.data)