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

如何解决购物车+按钮点击触发的GET 500内部服务器错误?

Django购物车+按钮点击500错误排查与解决

错误原因分析

  • 变量未定义错误:plus_cart视图中返回的data字典使用了未定义的item_qty变量,实际应该引用修改后的cart.item_qty。
  • 外键查询不匹配:Cart.objects.get(product=product_id)中,product是外键字段,直接传入ID值会导致查询匹配失败,正确写法应为Cart.objects.get(product_id=product_id)。
  • 前端未实时更新:AJAX请求成功后未同步更新页面上的商品数量,导致必须刷新才能看到变化。
  • jQuery重复引入:页面同时加载两个不同版本的jQuery,可能引发脚本冲突。
  • HTML结构错误:<tr>标签放在了{% for cart in cart %}循环外部,导致所有购物车项被包裹在同一个表格行中,结构不符合规范。
  • 模板变量错误:隐藏输入框的value="{{product.ProdID}}"应为value="{{cart.product.ProdID}}",否则无法正确获取当前商品ID。

解决方案

1. 修复views.py中的plus_cart视图

def plus_cart(request):
    product_id = request.GET.get('prod_id')  # 用get避免KeyError
    try:
        # 外键字段用product_id参数查询,避免类型不匹配
        cart = Cart.objects.get(product_id=product_id)
        cart.item_qty += 1
        cart.save()
        # 使用已定义的cart.item_qty
        data = {
            'item_qty': cart.item_qty,
            'success': True
        }
        return JsonResponse(data)
    except Cart.DoesNotExist:
        # 处理购物车项不存在的异常
        data = {
            'success': False,
            'message': '购物车项不存在'
        }
        return JsonResponse(data, status=404)

2. 修复前端cartpage.html代码

{% extends 'base.html' %}
{% load static %}

{% block content %}
<div class="d-flex">
    <div class="border rounded p-4 m-4" style="width:1000px;">
        <p class="display-4 pl-4 ml-4">Shopping Cart</p>
        <hr>
        
        <table class="table table-fixed">
            <thead class="thead-dark">
                <tr>
                    <th></th>
                    <th class="w-5">Image</th>
                    <th>Product</th>
                    <th>Quantity</th>
                    <th>Price</th> 
                </tr>
            </thead>
        
            <tbody>
                {% for cart_item in cart %}  <!-- 重命名循环变量避免冲突 -->
                <tr>
                    <td><ion-icon name="close-outline"></ion-icon></td>
                
                    <input type="hidden" name="prodid" value="{{cart_item.product.ProdID}}" id="prodid-{{cart_item.product.ProdID}}" class="prodid">
                    <td class="w-5"><img src="{{ cart_item.product.ProdPic.url }}" style="height:80px; width:65px;" class="rounded-circle"></td>
                    <td>{{cart_item.product.ProdName}}</td>
                    
                    <td class="cart-product-quantity">
                        <input type="button" pid="{{ cart_item.product.ProdID }}" class="minus-cart btn btn-light btn-circle btn-sm" value="-">
                        <!-- 给数量span添加唯一ID,方便精准更新 -->
                        <span id="quantity-{{ cart_item.product.ProdID }}" min="1">{{ cart_item.item_qty }}</span>
                        <input type="button" pid="{{ cart_item.product.ProdID }}" class="plus-cart btn btn-light btn-circle btn-sm" value="+">
                    </td>
                        
                    <td>RM{{cart_item.product.ProdPrice}}</td>
                </tr>
                {% empty %}
                <tr>
                    <td colspan="5" class="text-center">购物车为空</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>

    <!-- 移除重复的jQuery,保留一个版本 -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
    <script>
        $(document).ready(function(){
            $('.plus-cart').click(function(){
                var id = $(this).attr("pid");
                var $quantitySpan = $('#quantity-' + id); // 获取当前商品的数量元素

                $.ajax({
                    type: "get",
                    url: "{% url 'plus_cart' %}",
                    dataType: 'json',
                    data: {
                        prod_id: id
                    },
                    success:function(data){
                        if(data.success){
                            $quantitySpan.text(data.item_qty); // 实时更新页面显示的数量
                        } else {
                            alert(data.message);
                        }
                    },
                    error:function(xhr){
                        console.log("请求失败:", xhr.responseText);
                    }
                });
            });
        });
    </script>
{% endblock %}

3. 验证urls.py配置

当前urls.py中的plus_cart路径配置正确,无需修改:

path('plus_cart/',views.plus_cart,name='plus_cart'),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 14:47:02