[Answered ]-How can I show in cart items in my index view?

1👍

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)

0👍

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%}

Leave a comment