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

Django购物车开发报错:Cart() takes no arguments求助

解决Django购物车模块的TypeError: Cart() takes no arguments错误

错误原因

  • 核心问题:Cart类的构造函数名称拼写错误,将Python类的标准构造函数__init__误写为__int__,导致实例化Cart(request)时,Python无法识别带参数的构造方法,抛出"takes no arguments"错误。
  • 次要问题:__iter__方法中查询Product时使用了错误的Django字段查询语法id_in,正确写法应为id__in。
  • 冗余代码:cart_detail视图中定义了products变量但未使用,可清理。

解决方案

1. 修复Cart类的构造函数

修改cart.py中的构造函数名称:

class Cart:
    # 将 __int__ 修正为 __init__
    def __init__(self, request):
        """
        Initialize the cart.
        """
        self.session = request.session
        cart = self.session.get(settings.CART_SESSION_ID)
        if not cart:
            cart = self.session[settings.CART_SESSION_ID] = {}
        self.cart = cart

2. 修复__iter__方法的查询语法

修改cart.py中__iter__方法的Product查询逻辑:

def __iter__(self):
    """
    Iterate over the items in the cart and get the products
    from the database
    """
    product_ids = self.cart.keys()
    # 将 id_in 修正为 id__in(Django字段查询双下划线语法)
    products = Product.objects.filter(id__in=product_ids)
    cart = self.cart.copy()
    for product in products:
        cart[str(product.id)]['product'] = product
    for item in cart.values():
        item['price'] = Decimal(item['price'])
        item['total_price'] = item['price'] * item['quantity']
        yield item

3. 清理冗余代码(可选)

修改views.py中的cart_detail视图,删除未使用的products变量:

def cart_detail(request):
    cart = Cart(request)
    for item in cart:
        item['update_quantity_form'] = CartAddProductForm(initial={
                            'quantity': item['quantity'],
                            'override': True})
    return render(request, 'cart/detail.html', {'cart': cart})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 00:10:16