Django DRF报错:return serializer_field.context[‘request‘].user,KeyError: ‘request‘

Django报错

return serializer_field.context['request'].user
KeyError: 'request'

在这里插入图片描述
报错原因:这是因为我使用的api_view而不是GenericAPIView(GenericAPIView会自动对context处理,而api_view不会)
所以视图中的接口应该这样写:

@api_view(["GET", "POST"])
def article_list(request, format=None):
    context = {
        "request": request,
    }
    if request.method == "GET":
        articles = Article.objects.all()
        serializer = ArticleSerializer(articles, many=True)
        return Response(serializer.data)
    elif request.method == "POST":
        print(request.data)
        print(request.user)
        serializer = ArticleSerializer(data=request.data, context=context)
        print(serializer)
        if serializer.is_valid():
            serializer.save(author=request.user)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

额外传递 context=context参数到自己的ArticleSerializer中

你可能感兴趣的:(Django,django,sqlite,数据库)