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

Django API无法获取POST请求数据,字段值均为None求助

问题原因

你用Postman发送的是JSON格式的POST请求,但Django的request.POST仅支持解析application/x-www-form-urlencoded(表单编码)类型的请求数据,因此无法从request.POST中获取到JSON字段值,返回None。另外你的Game模型中price是BigIntegerField,但请求里传的是浮点字符串,后续创建对象会触发类型错误,这个也需要修正。

解决方案

1. 修改视图函数,解析JSON请求体

导入json模块,从request.body中读取并解析JSON数据:

import json
from django.http import JsonResponse
from decimal import Decimal

def apiRequests(request):
    if request.method == "POST":
        # 解析JSON请求体
        try:
            data = json.loads(request.body)
        except json.JSONDecodeError:
            return JsonResponse({"error": "无效的JSON数据"}, status=400)
        
        name = data.get("name")
        publisher = data.get("publisher")
        price = data.get("price")
        
        print(name, publisher, price)
        
        # 处理price类型:根据模型字段做对应转换
        try:
            # 若模型用BigIntegerField,转成整数(示例:取整)
            # price_val = int(float(price))
            # 若后续改成DecimalField,转成Decimal类型
            price_val = Decimal(price)
            Game.objects.create(name=name, publisher=publisher, price=price_val)
        except (ValueError, TypeError):
            return JsonResponse({"error": "价格格式无效"}, status=400)
        
        return JsonResponse({"status": "success"})
    elif request.method == "GET":
        game_name = request.GET.get("name")
        games = Game.objects.filter(name=game_name)
        # API接口返回JSON格式结果
        game_list = [{"id": game.id, "name": game.name, "publisher": game.publisher, "price": game.price} for game in games]
        return JsonResponse({"games": game_list})
    # 非POST/GET请求返回错误
    return JsonResponse({"error": "不允许的请求方法"}, status=405)

2. 调整Postman请求设置

  • 在请求头中添加Content-Type: application/json
  • 请求体选择raw -> JSON格式,再发送你的JSON数据

3. 可选:修正模型的price字段类型

如果价格需要保留小数,建议把BigIntegerField改成DecimalField,更贴合业务需求:

from django.db import models

class Game(models.Model):
    name = models.CharField(max_length=200)
    publisher = models.CharField(max_length=200)
    # 保留2位小数,最大位数可根据需求调整
    price = models.DecimalField(max_digits=10, decimal_places=2)

    def __str__(self):
        return f"{self.id} {self.name}"

补充:兼容多类型请求

如果API需要同时支持表单提交和JSON请求,可以通过判断请求头的Content-Type分支处理:

def apiRequests(request):
    if request.method == "POST":
        if request.content_type == "application/json":
            data = json.loads(request.body)
        elif request.content_type == "application/x-www-form-urlencoded":
            data = request.POST
        else:
            return JsonResponse({"error": "不支持的请求格式"}, status=415)
        # 后续数据处理逻辑...

内容的提问来源于stack exchange,提问作者Chrisy455

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 02:24:29