self.user = serializer_field.context['request'].user KeyError: 'request

django DRF:

APIView和通用API的细节区别:

 

 使用CurrentUserDefault()时报错:

user = serializers.HiddenField(
default=serializers.CurrentUserDefault()

 报错如下:

File "C:\Users\sz.yu\Envs\Smartshop\lib\site-packages\rest_framework\fields.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参数

 

转载于:https://www.cnblogs.com/yushengzhou/p/9873140.html

你可能感兴趣的:(self.user = serializer_field.context['request'].user KeyError: 'request)