None

Iterating Dictionaries in Django Templates

January 17, 2010

You can access both the key and value parts of a python dictionary directly from django templates.

Create Dictionary

This code builds up a dictionary of contest names to number of events.

for row in rows:
    lContestName = row[2]
    try:
        lCountAlready = lResults[lContestName]
        lCountAlready += 1
    except KeyError:
        lCountAlready = 1
    lResults[lContestName] = lCountAlready

Django Template

The django template then displays this in a table.

{% for contestname, eventcount in Venue.contests.items %}
<tr>
<td class="contest"><a href="/contests/{{contest.slug}}/">{{contestname}}</a></td>
<td>{{eventcount}}</td>
</tr>
{% endfor %}