Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python/django for loop and list attributes

So, i'm studying the Django Book, and django documentation, and I can't understand this example:

<ul>
{% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
{% endfor %}
</ul>

This is about templates and i don't how to code the Context. How can i get attribute called "name" from a list ? If i create a dictionary it will be impossible to use for loop like in this example. I have coded it like this but it's not working:

athlete_list = {'name' = ['Athlete1', 'Athlete2', 'Athlete3']}
Context({'athlete_list':athlete_list})

if i change athlete_list variable to a normal list (not a dictionary) the "athlete.name" in the template won't work too. I don't think it's a mistake in a book, and it's probably very easy to solve, but i can't get it.

like image 732
Chris Avatar asked Dec 26 '22 14:12

Chris


1 Answers

I'd suspect that athlete_list is a QuerySet object containing Athlete models... (does that get mentioned anywhere?). The models will then have a .name or .age or .sport or whatever...

update - just looked at http://www.djangobook.com/en/2.0/chapter04.html - which actually doesn't appear to be the best example....

To keep the template as is, you can return a context of a list of dicts, eg:

[ {'name': 'bob'}, {'name': 'jim'}, {'name': 'joe'} ]
like image 143
Jon Clements Avatar answered Dec 31 '22 14:12

Jon Clements