Chris
Chris

Reputation: 527

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.

Upvotes: 4

Views: 962

Answers (3)

fuka1983
fuka1983

Reputation: 31

If you want to keep the template,you should return below.

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

Context({'athlete_list':athlete_list})

Upvotes: 3

Jon Clements
Jon Clements

Reputation: 142256

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'} ]

Upvotes: 5

dm03514
dm03514

Reputation: 55972

Your athlete_list is actually a dict

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

in templates you can access dictionary keys through . instead of through []

so in your template {{ athleate_list.name }}

would be a list of strings # ['Athlete1', 'Athlete2', 'Athlete3']

Upvotes: 2

Related Questions