首页 > 解决方案 > 如何从 Django 的愿望清单中删除产品?

问题描述

我的 Django 数据库中有愿望清单表,并且customer与愿望清单表相关,这意味着如果客户已登录,那么他/她可以添加产品wishlist,但我正在尝试从客户愿望清单中删除产品,但它正在重定向回来,请让我知道如何从客户愿望清单中删除产品。

这是我的models.py文件...

class Wishlist(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, default=None)
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
    quantity = models.IntegerField(default=0, null=True, blank=True)
    
def __str__(self):
    return str(self.id)

这是我的views.py文件...

def deletewishlist(request, id):
    customer=request.user.customer
    Wishlist.objects.filter(customer_id=customer.id, id=id).delete()
    messages.success(request, 'Product Remove From Wishlist...')
    return HttpResponseRedirect('/wishlist')

这是我的urls.py文件...

path('wishlist_item/deleteproduct/<int:id>', views.deletewishlist, name="deletewishlist"),

这是我的delete按钮代码,单击时会从愿望清单中删除产品...

<a class="primary-btn" href="/wishlist_item/deleteproduct/{{item.product.id}}" onclick="return confirm('Are you sure')">Delete</a>

标签: pythondjangodjango-modelsdjango-viewsdjango-templates

解决方案


您正在查询Wishlistid 而不是productid

利用:

def deletewishlist(request, id):
    customer=request.user.customer
    Wishlist.objects.filter(customer_id=customer.id, product=Product.objects.get(id=id)).delete()
    messages.success(request, 'Product Remove From Wishlist...')
    return HttpResponseRedirect('/wishlist')

推荐阅读