我正在使用 django 在我的电子商务网站上设置购物车功能。所有项目均以 cart_item
形式输入 MySQL 表中。
提问前,相关代码:
charm = False
if postdata.get('charm_sku'):
charm_sku = postdata.get('charm_sku','')
ch = get_object_or_404(Charm, sku=charm_sku)
#get products in cart
cart_products = get_cart_items(request)
product_in_cart = False
# check to see if item is already in cart
for cart_item in cart_products:
if cart_item.product.id == p.id:
if charm == True:
if cart_item.charm.id == ch.id:
# update the quantity if found
cart_item.augment_quantity(quantity)
product_in_cart = True
else:
if cart_item.charm.id == "":
# update the quantity if found
cart_item.augment_quantity(quantity)
product_in_cart = True
编辑:
我重新编写了代码,如上所示,导致 if cart_item.charm.id
抛出 attirbuteerror: 'NoneType' object has no attribute 'id'
。在某种程度上,我认为这改善了情况,因为我怀疑第一个看似“成功”的实际上是第一个 if charm == True
失败,因此从未测试第一个 如果 cart_item.charm.id == ch.id
。问题仍然是:当 For 循环清楚地声明了 cart_item,并且 cart_items 明确地同时具有 super 按钮列和分配给所述列的 id 时,为什么会引发 AttributeError?
编辑2: 我可以不从嵌套的 if 引用 cart_item 吗?这是我唯一能想到的事情,但同时我觉得我应该能够这样做,所以也许这是错误的?
最佳答案
NoneType
意味着您实际上拥有的是 None
,而不是类的实例。这可能意味着赋值失败或函数调用返回了意外结果。在 charm == False
的情况下,您对 cart_item
的分配可能会失败。检查设置这两个变量的任何代码(赋值或函数调用)。
关于python - 为什么同一对象在一个实例而不是其他实例中抛出 "NoneType"对象属性错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15890497/