sudheesh ks
sudheesh ks

Reputation: 371

Retrieving current user inside Serializer Method in Django Rest API

I have a serializer for user profiles in Django Rest:

class UserProfileSerializer(serializers.ModelSerializer):
    ......................
    ......................
    status = serializers.SerializerMethodField()
    def get_status(self, obj):
        user =  self.context['request'].user
            if obj.user.userprofile in user.followed_userprofiles_set.all():
                return "following"
            else:
                return "notfollowing"
    class Meta:
        model = UserProfile
        fields = (...., 'status',...)

And I have two views that use this serializer:

class Followers(APIView):

    def get(self, request, format=None):
        #user who follow current user
        users = request.user.userprofile.followers.all()
        userprofiles= UserProfile.objects.filter(user__in=users)
        serializer = UserProfileSerializer(userprofiles, many=True)
        return Response(serializer.data)

and

class Friends(mixins.ListModelMixin, generics.GenericAPIView):

    queryset = UserProfile.objects.all()
    serializer_class = UserProfileSerializer
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def get_queryset(self):
        .................
        .................
        return queryset

One view is using APIView and other is using genericAPIView. When i request from genericAPIView, its working properly. But when i request from APIView, its giving me key error. How to retrieve the current user inside serializer method when APIView is used?

Upvotes: 0

Views: 2809

Answers (1)

Rahul Gupta
Rahul Gupta

Reputation: 47846

Since you are manually instantiating the UserProfileSerializer in your APIView class without passing the context, KeyError exception gets raised.

You should pass the request in context parameter when instantiating the UserProfileSerializer in your APIView.

class Followers(APIView):

    def get(self, request, format=None):
        #user who follow current user
        users = request.user.userprofile.followers.all()
        userprofiles= UserProfile.objects.filter(user__in=users)
        context = {'request':request} # prepare serializer context
        serializer = UserProfileSerializer(userprofiles, many=True, context=context) # pass context
        return Response(serializer.data)

Upvotes: 1

Related Questions