How to get the authentication information in ModelViewSet?

Question:

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?

Asked By: whitebear

||

Answers:

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)
Answered By: Amin

yes you can do like this as the above answer or you can override the get_queryset method as well.

 def get_queryset(self):
        if self.request.user.is_authenticated:
            return whatever you want to return
        else:
            return None
Answered By: Tanveer Ahmad