[Django]-Django – Print dict in template

3👍

Finally I got it working by passing out.items() to the template and iterating over out, so:

views.py

context = {'out': out.items()}
return render(request, 'components_by_season.html', context)

in my temmplate:

{% for k,v in out %}
    <p>{{ k }}: {{ v.total_qty }}</p>
{% endfor %}

4👍

Assuming this is actually your real code, my_var is a dict, not a list. Iterating over a dict just gives you the keys; if you want the values as well, you should iterate over .items(). So:

<ul>
    {% for k, v in my_var.items %}
        <li>{{ k }}: {{ v.total_qty }}</li>
    {% endfor %}
</ul>

Note also, there is no product key; the name of the product is just the key in the outer dict.

2👍

If you just want to print this to debug, you can use the pprint filter:

{{out|pprint}}

Leave a comment