如何在索引视图中显示购物车中的商品?

How can I show in cart items in my index view?

我正在开发一个电子商务应用程序,我有一个显示我所有产品的模板。

我想显示购物车中有多少商品。但我似乎无法弄清楚如何从我的 for 循环中获取该信息。

我想检查我的 for 循环中的当前产品是否与该用户的 OrderItem 匹配。

我可以在详细视图中执行此操作,但我的 catalogue/index

代码:

模板

{% for product in products %}

{{product.title}} - {{product.quantity_in_cart}}

{% endfor %}

(截至目前,product.quantity_in_cart 什么都不做。我希望它显示购物车中有多少该产品)

查看

def product_index(request):
title = "My Products"
products = Product.objects.all()
order = get_cart(request)
cart = Order.objects.get(id=order.id, complete=False)
items = cart.orderitem_set.all()
context = {
'title' : title,
'products' : products,
'cart' : cart,
'items': items
}
return render(request, "store/product_index.html", context)

型号

class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
complete = models.BooleanField(default=False, null=True, blank=False)

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=True)
date_added = models.DateTimeField(auto_now_add=True)

class Product(models.Model):
name = models.CharField(max_length=64)
slug = models.SlugField(unique=True, null=True)
description = RichTextField(blank=True)
price = models.DecimalField(max_digits=8, decimal_places=2)
quantity = models.IntegerField()

添加一个名为 'cart' 的会话密钥,它可以是一个列表,列表中的每个项目都可以是一个包含 'name'、'quatity' 和价格的字典,因为用户是添加到购物车你添加你的会话变量,在模板中你可以使用这样的 for 呈现购物车

{% for product in request.session.carr%}
 {%endfor%}
def product_index(request):

    title = "My Products"
    products = Product.objects.all()
    order = get_cart(request)
    cart = Order.objects.get(id=order.id, complete=False)
    items = cart.orderitem_set.all()

    # Changes
    for product in products:
        qty = 0
        if items.filter(product=product).exists():
            qty = items.get(product=product).quantity
        setattr(product, 'quantity_in_cart', qty)

    context = {
    'title' : title,
    'products' : products,
    'cart' : cart,
    'items': items
    }
    return render(request, "store/product_index.html", context)