kron
kron

Reputation: 111

Django "for" loop and python dictionary problems

I'm having a couple of issues getting django templating for loop tag to go through this dictionary:

It is definitely being passed to the page ok as if I just do:

{% for event in events %}
   {{ event }} 
{% endfor %}

it writes 1,2,3 but when I try and do {{ event.start }} it just doesn't output anything...

    evs = {

        "1": {
            'start': '8:00:00',
            'end': '9:00:00',
            'name': 'test',
            'description': 'test',
            'image_url': 'http://test',
            'channel_url': 'http://test',
        },

        "2": {
            'start': '8:00:00',
            'end': '9:00:00',
            'name': 'test',
            'description': 'test',
            'image_url': 'http://test',
            'channel_url': 'http://test',
        },

        "3": {
            'start': '8:00:00',
            'end': '9:00:00',
            'name': 'test',
            'description': 'test',
            'image_url': 'http://test',
            'channel_url': 'http://test',
        }

    }

And this is my django code in the template:

    {% for event in events %}
            {{ event.end }}
            {{ event.name }}
            {{ event.description }}
            {{ event.image_url }}
            {{ event.channel_url }}
    {% endfor %}

Any help would be really appreciated!

Thanks

Upvotes: 2

Views: 2940

Answers (2)

Felix Kling
Felix Kling

Reputation: 816422

Well, in your case, event is the always the key of one entry (which is a string), not the object itself, so event.start cannot work.

Have look at the documentation. You could do:

{% for key, event in events.items %}
        {{ event.end }}
        {{ event.name }}
        {{ event.description }}
        {{ event.image_url }}
        {{ event.channel_url }}
{% endfor %}

Upvotes: 5

Bernhard Vallant
Bernhard Vallant

Reputation: 50786

If you are just iterating over events you are just iterating over the dictonary's keys; you need to iterate over the dictionary's values: {% for event in events.values %}!

Upvotes: 6

Related Questions