7

i have my serializer like this

class PublicacionSerializer(serializers.ModelSerializer):
    usuario = UserSerializer2()
    likeado = serializers.SerializerMethodField()

    class Meta:
        model = Publicacion
        fields = ('id','usuario', 'likeado')

    def get_likeado(self, obj):
        user = self.context['request'].user
        try:
            like = Like.objects.get(publicacion=obj, usuario=user)
            return like.id
        except Like.DoesNotExist:
            return False

so i use that seriaizer in another one:

class EstadoSerializer(serializers.ModelSerializer):
    publicacion = PublicacionSerializer(read_only=True)

in views.py i have

class ModificarEstadoMixin(object):
    queryset = Estado.objects.all()
    serializer_class = EstadoSerializer

class ModificarEstadoDetail(ModificarEstadoMixin, RetrieveUpdateAPIView):
    permission_classes = (permissions.IsAuthenticated,
              CanModifEstado,)
    pass

when i access to the url for know if an user has liked to a post i got a KeyError 'request' in code line

user = self.context['request'].user

anyone knows how to solve it?

0

1 Answer 1

18

When you call that serializer, you have to pass context from view like

MySerializer(context={'request': request})
Sign up to request clarification or add additional context in comments.

3 Comments

or you can call get_serializer method, which will pass context for you
i don't know where i should to put it @itzmeontv i edited my post
Hi there. Where I should properly use the context={'request': request} using the example posted by the question? I'm getting NameError: name 'request' is not defined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.