Django rest框架request.data引发错误

时间:2017-05-15 05:26:09

标签: python django django-rest-framework

我正在使用Django Rest Framework。在我看来,两者都会出现像request instance has no attribute 'data'这样的错误。我尝试了很多但没有找到任何东西。我是否必须添加任何中间件或其他东西? DRF如何从request.POST和request.GET中检索数据。我的观点是基于功能的。

def list(request, format=None):
    if request.method == 'POST':
        serializer = CustomerSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

1 个答案:

答案 0 :(得分:4)

@api_view装饰器丢失。要在DRF中获取request.data,您必须调用装饰器@api_view或从APIView类延伸 如果您使用的是基于功能的视图,请使用api_view装饰器

来自rest_framework.decorators的

导入api_view

@api_view
def list(request):
    if request.method == 'POST':
        serializer = CustomerSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

对于基于类的视图,从APIView扩展

from rest_framework.views import APIView

class List(APIView):

    def post(self, request):
        serializer = CustomerSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

文档:DRF request