You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Django REST Framework开发API时POST请求返回name和description字段必填错误的问题求助

解决Django API POST请求提示字段必填的问题

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/json in your request headers. Without this, DRF won't parse the JSON payload into request.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 18:09:10