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

Django中request.POST为空,无法获取POST请求数据求助

解决Django中无法获取POST请求数据的问题

问题原因分析

  1. request.data不存在:request.data是Django REST Framework(DRF)专属Request对象的属性,你当前拿到的是原生Django的WSGIRequest,因此没有该属性。
  2. request.body报错:RawPostDataException提示请求体已被其他代码(如父类方法、中间件)读取过,Django的请求流仅支持一次读取操作。
  3. request.POST为空:只有当请求的Content-Type为application/x-www-form-urlencoded或multipart/form-data时,Django才会自动将数据解析到request.POST中;若请求是JSON格式(Content-Type: application/json),数据不会被解析到这里。

解决方案

1. 适配JSON格式的POST请求

如果你的请求是JSON格式,用DRF的Request包装原生请求,自动解析数据:

from rest_framework.request import Request

def list_apps(self, request, provider=None, client_id=None):
    # 用DRF Request包装原生请求,自动解析JSON
    drf_request = Request(request)
    client_id = drf_request.data.get('client_id')
    print(client_id)
    
    apps = super().list_apps(request=request, provider=provider, client_id=client_id)
    return apps

2. 手动读取并解析请求体

若需直接操作原生请求体,需在父类方法调用前完成读取(避免重复读取报错):

def list_apps(self, request, provider=None, client_id=None):
    # 先读取请求体内容
    body_content = request.body
    # 解析JSON数据
    import json
    try:
        data = json.loads(body_content)
        client_id = data.get('client_id')
    except json.JSONDecodeError:
        # 兼容非JSON格式请求
        client_id = request.POST.get('client_id')
    print(client_id)
    
    apps = super().list_apps(request=request, provider=provider, client_id=client_id)
    return apps

3. 确认请求的Content-Type

检查请求头设置:

  • 表单提交需设置Content-Type: application/x-www-form-urlencoded,此时request.POST会正常解析数据。
  • JSON请求需设置Content-Type: application/json,再用上述对应方法解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 14:03:15