ComputerLocus
ComputerLocus

Reputation: 3618

Iterate over one key's dictionary in another dictionary in a Django template

I have a dictionary that looks like the following:

timeTables = {
        'today': {'date_start': datetime.now(), 'date_end': None},
        'yesterday': {'date_start': (datetime.now() - timedelta(days=1)), 'date_end': None},
        'week': {'date_start': (datetime.now() - timedelta(weeks=1)), 'date_end': datetime.now()},
        'month': {'date_start': (datetime.now() - timedelta(days=30)), 'date_end': datetime.now()},
    }

I want to output the today keys dictionary elements in a for loop within the Django template.

I can accomplish this in normal Python via:

for key, value in timeTables['today'].items():
        print key, value

But this same thing won't work in a Django template.

Doing this gives an error:

{% for key, value in data['today'].items %}
    {{ key }} {{ value }}
{% endfor %}

TemplateSyntaxError at /
Could not parse the remainder: '['today'].items' from 'data['today'].items'

Upvotes: 1

Views: 479

Answers (2)

Holt
Holt

Reputation: 37706

In Django templates, you cannot use the data['today'] syntax to access the value of a dictionnary, you need to use the . (data.today):

{% for key, value in data.today.items %}
    {{ key }} {{ value }}
{% endfor %}

Upvotes: 2

Ajay Gupta
Ajay Gupta

Reputation: 1285

try this: If you want only dictionary field with only 'today' key then simply send data['today'] from view {'data': data['today']} and then render it like:

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

If you want whole dictionary to be sent then,

{% for key, value in data.items %}
    {% for k,v in value.items %}
     {{k}} {{v}}
    {% endfor %}
{% endfor %}

Upvotes: 0

Related Questions