self.user = serializer_field.context['request'].user KeyError: 'request
Posted yushengzhou
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了self.user = serializer_field.context['request'].user KeyError: 'request相关的知识,希望对你有一定的参考价值。
django DRF:
APIView和通用API的细节区别:
使用CurrentUserDefault()时报错:
user = serializers.HiddenField(
default=serializers.CurrentUserDefault()
)
报错如下:
File "C:Userssz.yuEnvsSmartshoplibsite-packages est_frameworkfields.py", line 271, in set_context
self.user = serializer_field.context[‘request‘].user
KeyError: ‘request‘
这是因为我使用的APIView而不是GenericAPIView(GenericAPIView会自动对context处理,而APIView不会)
所有视图中序列化应该这样写:
def post(self, request, format=None):
context = {
"request":request,
}
serializer = UserMessageCreateSerializer(data=request.data, context=context)
if serializer.is_valid(raise_exception=True):
serializer.save()
return Response(serializer.data, status=HTTP_201_CREATED, content_type="application/json")
额外传递 context=context参数
以上是关于self.user = serializer_field.context['request'].user KeyError: 'request的主要内容,如果未能解决你的问题,请参考以下文章