从购物车中移除产品时遇到错误。当我通过设置数量将产品添加到购物车中并单击“删除”时,会显示错误。
分配前引用的本地变量“产品”
我在models.py文件中有产品,并通过导入模型从产品中引用了它,并尝试通过更改名称来进行尝试,但是仍然出现错误。
views.py
def update_cart(request,slug):
request.session.set_expiry(1200000)
try:
qty=request.GET.get('qty')
update_qty=True
except:
qty=None
update_qty=False
try:
the_id=request.session['cart_id']
except:
new_cart=Cart()
new_cart.save()
request.session['cart_id']=new_cart.id
the_id=new_cart.id
cart = Cart.objects.get(id=the_id)
try:
product=Product.objects.get(slug=slug)
except Product.DoesNotExist:
pass
except:
pass
cart_item,created=CartItem.objects.get_or_create(cart=cart,product=product)
if created:
print("yeah")
if update_qty and qty:
if int(qty)<=0:
cart_item.delete()
else:
cart_item.quantity=qty
cart_item.save()
else:
pass
return HttpResponseRedirect(reverse("carts:cart"))
models.py
class CartItem(models.Model):
cart=models.ForeignKey('Cart',on_delete=models.SET_NULL,null=True,blank=True)
product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True,blank=True)
accessory = models.ForeignKey(Accessories,on_delete=models.SET_NULL,null=True,blank=True)
quantity=models.IntegerField(default=1)
updated = models.DateTimeField(auto_now_add=True,auto_now=False)
line_total=models.DecimalField(default=10.99,max_digits=1000,decimal_places=2)
timestamp = models.DateTimeField(auto_now_add=True,auto_now=False)
objects = CartManager()
def __unicode__(self):
try:
return str(self.cart.id)
except:
return self.product.title
如果有人可以帮助您,将不胜感激吗?
注意 我看到了stackoverflow的其他链接,但没有帮助。
答案 0 :(得分:0)
您的产品变量位于try
块中,而python解释器看不到它。您可以在try块之外创建它:
....
product = None
try:
product=Product.objects.get(slug=slug)
或者在分配产品之后将处理该产品的逻辑移到try块中
cart = Cart.objects.get(id=the_id)
try:
product=Product.objects.get(slug=slug)
cart_item,created=CartItem.objects.get_or_create(cart=cart,product=product)
if created:
print("yeah")
if update_qty and qty:
if int(qty)<=0:
cart_item.delete()
else:
cart_item.quantity=qty
cart_item.save()
else:
pass
return HttpResponseRedirect(reverse("carts:cart"))
except Product.DoesNotExist:
pass
except:
pass