Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Key error 'request' in serializer

I'm trying to get the current user in my serializer, to evaluate a condition (did user like this post?), this answer is what I tried but it doesn't seem to work:

def current_user(self):
    return self.context['request'].user

class PostSerializer(serializers.ModelSerializer):
    liked = serializers.SerializerMethodField()

    def get_liked(self, obj):
        return str(current_user(self))

    class Meta:
        model = Track
        fields = ('foo', 'liked')

And my very simple view:

@api_view(['GET'])
def post_item(request, pk):
        serializer = PostSerializer(post)
        return Response(serializer.data)

When trying to get_liked this is error is raised:

KeyError at /api/posts/1

'request'

Am I missing something here?

like image 764
Sebastian Olsen Avatar asked Feb 08 '23 05:02

Sebastian Olsen


1 Answers

You can send the context from your view to the serializer like this:

@api_view(['GET'])
def post_item(request, pk):
    serializer = PostSerializer(track, context={'request': request})
    return Response(serializer.data)
like image 189
fips Avatar answered Feb 19 '23 18:02

fips