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

Viewed 155

I'm working on an ecommerce app, and I have a template that displays all my products.

I want to show how many of the item are in the cart. But I can't seem to figure out how to get that information from my for loop.

I want to check if the current product in my for loop matches with an OrderItem for that user.

I'm able to do this in the detail view but not my catalogue/index

Code:

template

{% for product in products %}

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

{% endfor %}

(As of right now, product.quantity_in_cart does nothing. I would like it to show how many of this product are in the cart)

view

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)

models

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()
2 Answers
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)

Add a session key called 'cart' which can be a list and each item in the list can be a dictionary containing 'name', 'quatity' and price, as the the user is adding to the cart you add you the session variable and in the template you can render the cart using a for like this

{% for product in request.session.carr%}
 {%endfor%}
Related