我正在使用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)
答案 0 :(得分:4)
@api_view
装饰器丢失。要在DRF中获取request.data
,您必须调用装饰器@api_view
或从APIView
类延伸
如果您使用的是基于功能的视图,请使用api_view装饰器
导入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