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

Django项目报错:'dict' object has no attribute 'code' 求助

问题解决:'dict' object has no attribute 'code'

错误原因

你遇到的错误是因为Python字典不能用点号(.)访问键值,API返回的product是字典类型,必须用方括号[]来获取code字段的值。另外,cart.add()的参数传递也存在问题。

修正后的代码

def cart_add(request, code):
    url = 'http://myapi/Product/GetProducts'
    response = requests.get(url)
    content = response.json()
    all_products = content['products']
    
    for product in all_products:
        # 修正:用方括号访问字典键值
        if product['code'] == code:
            cart = Cart(request)
            # 根据django-shopping-cart的要求传递正确参数
            # 示例:如果需要传递产品ID、名称等信息
            cart.add(product_id=product['code'], name=product['designation'], quantity=1)
            # 或者如果你的购物车支持直接传入字典(需自定义配置):
            # cart.add(product=product)
            break  # 找到匹配产品后退出循环,避免无效遍历
    
    return render(request, 'shop/detail.html')  # 修正拼写错误:deatil → detail

关键修正点

  • 字典访问方式:将product.code改为product['code'],这是Python字典获取值的正确方式。
  • 购物车添加逻辑:cart.add()通常需要传入产品对象(如Django模型实例)或具体参数(如product_id、name、quantity等),直接传入字符串类型的code不符合要求,请根据你的购物车配置调整参数。
  • 循环优化:找到匹配产品后加入break语句,减少不必要的循环迭代。
  • 模板路径修正:修正了模板名称的拼写错误deatil.html→detail.html。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:05:34