Search code examples
djangocartdbcontext

Context data not passing to Django templates


My cart view. I have passed context on return but it doesn't appear on the templates. If i print the

    def cart(request):
        total = 0
        quantity = 0
        cart_items = None
        tax = None
        grand_total = None
    
        try:
            cart = Cart.objects.get(cart_id=_cart_id(request))
            cart_items = CartItem.objects.filter(cart=cart, is_active=True)
    
            for cart_item in cart_items:
                total += (cart_item.product.price * cart_item.quality)
                quantity = cart_item.quality
    
            tax = (total / 100) * 2
            grand_total = total + tax
    
        except:
            pass
    
        context = {
            'total': total,
            'quantity': quantity,
            'cart_items': cart_items,
            'tax': tax,
            'grand_total': grand_total,
        }
        return render(request, 'c.html', context)

Html Template. Here I created a for loop to get items from the array. But It doesn't show any objects from the array. But always print "Item" string for each object.

{% extends 'base.html' %}
{% load static %}

{% block content %}
{% for item in cart_items %}

<h1>item.product.product_name </h1>

{% endfor %}
{% endblock %}

Solution

  • You code is not correct i think. Try this:

    {% extends 'base.html' %}
    {% load static %}
    
    {% block content %}
    {% for item in cart_items %}
    {{item.product.product_name}}
    {% endfor %}
    {% endblock %}