Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django "for" loop and python dictionary problems

Tags:

python

django

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

like image 859
kron Avatar asked Jul 16 '26 00:07

kron


2 Answers

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 %}!

like image 178
Bernhard Vallant Avatar answered Jul 17 '26 15:07

Bernhard Vallant


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 %}
like image 37
Felix Kling Avatar answered Jul 17 '26 13:07

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!