我想检查类别页面中的产品是否存在于购物车中,然后使用 django 和 jinja 在网页中显示添加的图标

I want to check whether the products in the category page exists in cart then show a added icon in webpage using django and jinja

我有一个类别页面(有多个产品在它们下面有添加到卡片按钮),其中我有一个添加到购物车按钮,但如果该产品已经存在于购物车中,我想显示一个添加到购物车图标instead.I 我无法找出检查的方法。这是我的 models.py

class Order(models.Model):
    customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True,blank=True)
    date_ordered=models.DateTimeField(auto_now_add=True)
    complete=models.BooleanField(default=False,null=True,blank=False)
    transaction_id=models.CharField(max_length=100,null=True)
class OrderItem(models.Model):
    product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True)
    order=models.ForeignKey(Order,on_delete=models.SET_NULL,null=True)
    quantity=models.IntegerField(default=0,null=True,blank=False)
    date_added=models.DateTimeField(auto_now_add=True)
class Product(models.Model):
    category = models.ForeignKey(Category, on_delete = models.CASCADE)
    productid=models.CharField(max_length=30)
    name=models.CharField(max_length=30)

这是我的 views.py

def category(request):
context = {
    'types' : Category.objects.all(),
    'prods': Product.objects.filter(),
    'cartItems':[],
    'in_cart': False,
    
}
if request.user.is_authenticated:
    customer=request.user.customer
    order, created=Order.objects.get_or_create(customer=customer, complete=False)
    cartItems=order.get_cart_items,     
    items=order.orderitem_set.all()
    context['in_cart'] =order.orderitem_set.filter(product__productid=id).exists()    
return render(request,"category.html",context)

这是我的 html 按钮代码

{% if user.is_authenticated %}
{% if in_cart %}
<button data-product={{product.id}} data-action="add"
class="btnabc btnabc-warning update-cart">Added</button>
 {% else %}
<button data-product={{product.id}} data-action="add"
class="btnabc btnabc-warning update-cart">Add to Cart</button>
{% endif %}
 {% else %}
<button class="btnabc btnabc-warning"><a href="/login/">Add to
Cart</a></button>
{% endif %}

但即使产品不在购物车中它似乎也不起作用,它显示已添加并相应地显示按钮。如有任何帮助,我们将不胜感激。

context['list_cart'] = order.orderitem_set.values_list('product__id', flat=True)

values_list return 仅选择字段的列表(这里是 product__id

结果看起来像那样[55, 88, 99, 123, 42 ...ect]

因此在模板中您可以搜索 product.id 是否在列表中

html:

{% if product.id in list_cart %}
    this id already in cart
{% else %}
    add to cart
{% endif %}