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参数

 

posted on 2018-10-29 20:43  工大只有一个阿锤  阅读(751)  评论(0编辑  收藏  举报

导航