I can't loop trough a dictionnary in my Django Template


I’m trying to loop trough a dictionnary to create a simple table with the keys in a column and the values in the other.

So in my view I create the dictionnary vegetables_dict. I loop trhough the "items" of a "cartitem". If the item doesn’t alrady exists I created a key with the name of a ForignKey of "item" and a value with its attribute quantity. Otherwise I increment the already existing key with the corresponding quantity

def dashboard_view(request):

    carts = Cart.objects.filter(cart_user__isnull = False)
    cartitems = CartItem.objects.all()

    vegetables_dict = {}
    for item in cartitems:
        if item.stock_item.product_stockitem.name in vegetables_dict:
            vegetables_dict[item.stock_item.product_stockitem.name] += item.quantity
        else :
            vegetables_dict[item.stock_item.product_stockitem.name] = item.quantity

    context = {
        'carts' : carts,
        'cartitems' : cartitems,
        'items' : vegetables_dict
    return render(request, "maraicher/dashboard.html", context)

In the template i Tried :

                    <th colspan="2"> Récapitulatif de récole</th>

                {% for key, value in items.item %}
                {% endfor %}


{{items}} render the dictionnary but the table is empty.

Any idea what is happening?

I aslo tried

{% for item in items %}
{% endfor %}
Asked By: VincentAb



This is how it should be in Django’s template:

            {% for key, value in items.items %}
                <td>{{ key }}</td>
                <td>{{ value }}</td>           
            {% endfor %}
Answered By: NixonSparrow

As mentionned by @user2390182 a "s" was missing, the correct syntaxe is

{% for key, value in items.items %}

Answered By: VincentAb

You must try this


{% for item in items.items() %}
{% endfor %}
Answered By: 007Coding