Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework KeyError 'request'

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?

like image 775
PoYo Rivera Avatar asked Mar 06 '17 11:03

PoYo Rivera


1 Answers

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

MySerializer(context={'request': request})
like image 150
itzMEonTV Avatar answered Oct 23 '22 03:10

itzMEonTV