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

使用django-shopping-cart 0.1添加字典商品到购物车报错求助

问题根源

django-shopping-cart 0.1的Cart类是为Django ORM模型实例设计的,所有方法均通过.访问对象属性(如product.id、product.name),但你传入的是Python字典——字典只能通过[]访问键值,因此必然触发「字典对象没有id属性」的报错。仅修改id=product.code无法解决问题,因为后续product.name、product.price、product.image.url等属性访问仍会报错。

解决方案

提供两种可行方案,按需选择:

方案一:修改Cart类适配字典商品

直接修改cart.py中的核心方法,将所有属性访问改为字典键访问,并匹配你商品字典的键名(如价格键为prix、编码键为code):

class Cart(object):
    def __init__(self, request):
        self.request = request
        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

    def add(self, product, quantity=1, action=None):
        id = product["code"]
        newItem = True
        if str(id) not in self.cart.keys():
            self.cart[id] = {
                'userid': self.request.user.id if self.request.user.is_authenticated else None,
                'product_id': id,
                'name': product["name"],
                'quantity': 1,
                'price': str(product["prix"]),
                'image': ""  # 你的字典无image字段,设为空字符串
            }
        else:
            newItem = False
            for key, value in self.cart.items():
                if key == str(id):
                    value['quantity'] += 1
                    self.save()
                    break
            if newItem:
                self.cart[id] = {
                    'userid': self.request.user.id if self.request.user.is_authenticated else None,
                    'product_id': id,
                    'name': product["name"],
                    'quantity': 1,
                    'price': str(product["prix"]),
                    'image': ""
                }
        self.save()

    def remove(self, product):
        product_id = str(product["code"])
        if product_id in self.cart:
            del self.cart[product_id]
            self.save()

    def decrement(self, product):
        product_id = str(product["code"])
        for key, value in self.cart.items():
            if key == product_id:
                value['quantity'] -= 1
                if value['quantity'] < 1:
                    del self.cart[key]
                self.save()
                break
            else:
                print("Something Wrong")

    def save(self):
        self.session[settings.CART_SESSION_ID] = self.cart
        self.session.modified = True

    def clear(self):
        self.session[settings.CART_SESSION_ID] = {}
        self.session.modified = True

同时修正视图函数中的变量名错误:

def cart_add(request, code):
    dico={"produits":[{"code":"fg21","name":"coca cola","prix":1500}, 
    {"code":"br21","name":"pomme","prix":1800}]}
    all_produits=dico['produits']
    selected_product = next((item for item in all_produits if item["code"] == code), None)
    if selected_product is not None:
        cart = Cart(request)
        cart.add(product=selected_product)
    context = {'cart': cart} if 'cart' in locals() else {}
    return render(request, 'cart/detail.html', context)

方案二:将字典转换为可属性访问的对象

无需修改Cart类,通过types.SimpleNamespace将字典转为支持.访问的对象,适配Cart类的属性调用逻辑:

from types import SimpleNamespace

def cart_add(request, code):
    dico={"produits":[{"code":"fg21","name":"coca cola","prix":1500}, 
    {"code":"br21","name":"pomme","prix":1800}]}
    all_produits=dico['produits']
    selected_product = next((item for item in all_produits if item["code"] == code), None)
    if selected_product is not None:
        # 转换字典为可属性访问的对象,映射Cart类所需属性
        product_obj = SimpleNamespace(
            id=selected_product["code"],
            name=selected_product["name"],
            price=selected_product["prix"],
            image=SimpleNamespace(url="")  # 模拟image.url属性,避免报错
        )
        cart = Cart(request)
        cart.add(product=product_obj)
    context = {'cart': cart} if 'cart' in locals() else {}
    return render(request, 'cart/detail.html', context)
补充说明

django-shopping-cart 0.1版本较老旧,可能已停止维护。若后续需接入Django模型,建议考虑更主流的购物车库(如django-cart、django-oscar)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 02:55:22