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

Django购物车点减少按钮报KeyError与JSONDecodeError如何解决

问题根源

报错完全由cart.html模板中减少按钮的自定义数据属性书写错误导致:减少按钮未正确设置data-product属性,JS读取productId为空,发送空请求体到后端,触发JSON解析失败与KeyError。

修复步骤

1. 修正模板属性错误

打开cart.html,找到数量调整区域的两个按钮代码,做如下修改:

  • 原减少按钮代码:
<img data=product-{{item.product.id}} data-action="remove" class="chg-quantity update-cart" src="{% static 'images/arrow_downjfif' " alt="d">

替换为:

<img data-product="{{item.product.id}}" data-action="remove" class="chg-quantity update-cart" src="{% static 'images/arrow_down.jfif' %}" alt="d">
  • 原增加按钮也存在语法瑕疵,同步修正:
<img data-product={{item.product.id}} data-action="add" class="chg-quantity update-cart" src="{% static 'images/arrow_up.jpg' " alt="P">

替换为:

<img data-product="{{item.product.id}}" data-action="add" class="chg-quantity update-cart" src="{% static 'images/arrow_up.jpg' %}" alt="P">

2. 优化JS代码(可选,避免潜在问题)

  • 修正变量声明拼写错误,把JS第一行的ar updateBtns改为var updateBtns
  • 请求路径改为绝对路径,避免多级路由下路径匹配错误:把var url='update/'改为var url='/update/'

3. 后端增加容错处理(可选,降低异常概率)

修改updateItem视图,增加参数校验和异常捕获,避免后续类似请求直接返回500:

def updateItem(request):
    if request.method != 'POST':
        return JsonResponse({'status': 'fail', 'msg': '请求方法不支持'}, status=405)
    try:
        data = json.loads(request.body)
    except json.JSONDecodeError:
        return JsonResponse({'status': 'fail', 'msg': '请求格式错误'}, status=400)
    productId = data.get('productId')
    action = data.get('action')
    if not productId or not action:
        return JsonResponse({'status': 'fail', 'msg': '参数缺失'}, status=400)
    
    customer = request.user
    product = Product.objects.get(id=productId)
    # 补充complete=False参数,和其他视图逻辑保持一致,避免生成重复无效订单
    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
    orderitem.save()

    if orderitem.quantity <= 0:
        orderitem.delete()

    return JsonResponse({'status': 'success'}, safe=False)

做完以上修改后清空浏览器缓存重新测试,增减按钮功能即可恢复正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:24:02