[Fixed]-Retrieving current user inside Serializer Method in Django Rest API

1👍

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)

Leave a comment