【问题标题】:How to remove products from cart in Django?如何在 Django 中从购物车中删除产品?
【发布时间】: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


【解决方案1】:

你向模板发送什么查询,你能提供吗?

def remove_from_cart(request, id):
    the_id = request.session['cart_id']
    card = Cart.objects.filter(id=the_id)
    if card.exists():
        cartitem = CartItem.objects.filter(card_id=card.first().id)
        if cartitem.exists():
            cartitem.delete()
        return HttpResponseRedirect(reverse("cart"))
    return HttpResponseRedirect(reverse("cart"))

【讨论】:

  • 非常感谢@Marin 先生。但问题仍然存在。它没有显示任何错误,但产品没有删除。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-17
  • 2022-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多