【发布时间】:2019-10-12 18:25:06
【问题描述】:
我正在编写从购物车中删除产品的代码,但我遇到了一些问题。首先是当我单击删除时,产品没有从购物车中删除,其次是在我的 urls.py 中,我添加了正则表达式在 id 上用于从购物车中删除产品。但是当我单击删除时,该 id 不会显示在 url 中。
Views.py
def remove_from_cart(request,id):
try:
the_id=request.session['cart_id']
cart = Cart.objects.get(id=the_id)
except:
return HttpResponseRedirect(reverse("cart"))
cartitem=CartItem.objects.get(id=id)
cartitem.cart=None
cartitem.save()
return HttpResponseRedirect(reverse("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)
def __unicode__(self):
try:
return str(self.cart.id)
except:
return self.product.title
urls.py
url(r'^cart/(?P<id>\d+)/$', remove_from_cart, name='remove_from_cart'),
template.html
<td><a href="{% url 'remove_from_cart' item.id %}">Remove</a></td>
如果有人可以提供帮助,将不胜感激?
注意:我在 stackoverflow 上搜索了不同的链接,但没有任何帮助。
【问题讨论】:
-
能否请您检查会话中是否有cart_id?
-
是的先生,因为我已经使用会话更新了购物车。
标签: django django-models django-forms django-templates django-views