使用Django REST Framework开发API时POST请求返回name和description字段必填错误的问题求助
Hey, I spot the root cause right away—your POST request handling is using the wrong way to access the incoming data.
问题原因
In Django REST Framework, request.POST only works for form-encoded data (like data submitted from HTML forms). If you're sending a JSON payload (which is standard for APIs), DRF parses that data into request.data instead. Since you're passing request.POST to the serializer, it's not seeing the name and description values you're sending, hence the "required field" errors.
修复代码
Update your views.py POST handler to use request.data instead of request.POST:
@api_view(['GET','POST']) def home(request): if request.method == 'GET': movies=Movie.objects.all() serializer=MovieSerializer(movies,many=True) return Response(serializer.data) if request.method == 'POST': # 替换request.POST为request.data以兼容JSON格式请求 serializer=MovieSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors)
额外检查点
Make sure your POST request includes the correct header:
- Set
Content-Type: application/jsonin your request headers. Without this, DRF won't parse the JSON payload intorequest.data, and you might still run into issues.
That should fix the required field errors and let your serializer properly process the incoming data.
内容的提问来源于stack exchange,提问作者priston

