Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

     <table>
            <thead>
                <tr>
                    <th colspan="2"> Récapitulatif de récole</th>
                </tr>
            </thead>
            <tbody>
                <th>Produit</th>
                <th>Quantité</th>
                <div>{{items}}</div>

                {% for key, value in items.item %}
                <tr>
                    <td>{{key}}</td>
                    <td>{{value}}</td>           
                </tr>
                {% endfor %}

            </tbody>
       </table>

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

Any idea what is happening?

I aslo tried

{% for item in items %}
   <tr>
      <td>{{item}}</td>
      <td>{{item.item}}</td>           
   </tr>
{% endfor %}

>Solution :

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

            {% for key, value in items.items %}
            <tr>
                <td>{{ key }}</td>
                <td>{{ value }}</td>           
            </tr>
            {% endfor %}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading