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

Django报错:'WSGIRequest' object has no attribute 'data' 求助

问题

编写基于函数的updateItem视图加载JSON数据时,出现报错:'WSGIRequest' object has no attribute 'data',同时JS中的fetch POST请求也受此影响。相关代码如下:

Views.py

def updateItem(request):  
    
    data = json.loads(request.data)
    
    productId = data['productId']
    action = data['action']
    print("productID", productId, "action", action)
    customer = request.user.customer
    product = Product.objects.get(id=productId)
    order, created = Order.objects.get_or_create(customer=customer,complete=False)

    orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)
    
    
    if action == 'add':
        orderItem.quantity = (orderItem.quantity + 1)
    elif action == 'remove':
        orderItem.quantity = (orderItem.quantity - 1)
    orderItem.save()
    
    if orderItem.quantity <= 0:
        orderItem.delete()
        
    return JsonResponse("Item was added!", safe=False)

JS 文件

function updateUserOrder(productId, action) {
    console.log('User is logged in...');
    let url = '/update_item/';

    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': csrftoken,
        },
        body: JSON.stringify({ productId: productId, action: action }),
    })
        .then((res) => {
            return res.json();
        })
        .then((data) => {
            console.log('data', data);
        });
}

urls.py

urlpatterns = [
    path("",views.store,name="store"),
    path("cart/",views.cart,name="cart"),
    path("checkout/",views.checkout,name="checkout"),
    path("update_item/",views.updateItem,name="update_item"),
]
错误原因

Django原生的WSGIRequest对象没有data属性,这个属性是Django REST Framework(DRF)专属的Request类提供的特性。你误用了DRF的写法,但当前视图是普通Django视图,不是DRF的API视图,因此触发报错。

修复方案

修改Views.py

将request.data替换为Django原生视图获取JSON数据的方式:通过request.body读取原始请求体,再用json.loads解析。同时增加请求方法校验、参数校验和异常处理,提升代码健壮性:

import json
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required

@login_required  # 强制用户登录,避免未登录时访问request.user.customer报错
def updateItem(request):  
    # 仅处理POST请求
    if request.method != 'POST':
        return JsonResponse({"error": "仅支持POST请求"}, status=400)
    
    try:
        # 读取并解析请求体中的JSON数据
        data = json.loads(request.body)
    except json.JSONDecodeError:
        return JsonResponse({"error": "无效的JSON格式"}, status=400)
    
    # 校验必要参数是否存在
    productId = data.get('productId')
    action = data.get('action')
    if not productId or not action:
        return JsonResponse({"error": "缺少productId或action参数"}, status=400)
    
    print("productID", productId, "action", action)
    
    # 校验商品是否存在
    try:
        product = Product.objects.get(id=productId)
    except Product.DoesNotExist:
        return JsonResponse({"error": "指定商品不存在"}, status=404)
    
    customer = request.user.customer
    order, created = Order.objects.get_or_create(customer=customer, complete=False)
    orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)
    
    # 处理增减逻辑
    if action == 'add':
        orderItem.quantity += 1
    elif action == 'remove':
        orderItem.quantity -= 1
    else:
        return JsonResponse({"error": "无效的操作类型,仅支持add/remove"}, status=400)
    
    orderItem.save()
    
    if orderItem.quantity <= 0:
        orderItem.delete()
        
    return JsonResponse({"message": "商品数量已更新"}, safe=False)

其他必要检查

  1. CSRF Token获取:确保JS中的csrftoken变量已正确从Cookie中读取,添加以下代码到JS文件开头:
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
const csrftoken = getCookie('csrftoken');
  1. URL一致性:确认JS中的/update_item/与urls.py中的路径完全匹配,无拼写错误。
  2. 登录状态校验:调用updateUserOrder前确保用户已登录,或依赖视图中的@login_required装饰器拦截未登录请求,避免request.user.customer抛出异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 20:50:25