gpt4 book ai didi

Django Rest框架KeyError 'request'

转载 作者:行者123 更新时间:2023-12-02 03:30:04 25 4
gpt4 key购买 nike

我有这样的序列化器

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

所以我在另一个序列化器中使用该序列化器:

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

在views.py中我有

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

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

当我访问网址以了解用户是否喜欢某个帖子时,我在代码行中收到 KeyError“请求”

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

谁知道怎么解决?

最佳答案

当您调用该序列化程序时,您必须从 View 传递上下文,例如

MySerializer(context={'request': request})

关于Django Rest框架KeyError 'request',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42624104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com