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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With