Python / django for loop and list attributes

So, I am studying the Django book and the django documentation, and I cannot understand this example:

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

This is about templates, and I don’t understand how to encode the context. How can I get the name attribute from the list? If I create a dictionary, it will not be possible to use for a loop, as in this example. I encoded it like this, but it does not work:

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

if I change the athlete_list variable to a regular list (not a dictionary), "athlete.name" in the template will not work either. I do not think this is a mistake in the book, and it is probably very easy to solve, but I cannot get it.

+4
source share
3 answers

I suspect athlete_list is a QuerySet object containing Athlete models ... (is this mentioned somewhere?). Then the models will have .name or .age or .sport or something else ...

update - just looked at http://www.djangobook.com/en/2.0/chapter04.html - which is actually not the best example ....

To save the template as is, you can return the context of the dicts list, for example:

 [ {'name': 'bob'}, {'name': 'jim'}, {'name': 'joe'} ] 
+5
source

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

 athlete_list = ({'name':'Athlete1'},{'name':'Athlete2'},{'name':'Athlete3'}) Context({'athlete_list':athlete_list}) 
+3
source

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 []

therefore, in your template {{ athleate_list.name }}

there will be a list of lines # ['Athlete1', 'Athlete2', 'Athlete3']

+2
source

Source: https://habr.com/ru/post/1447625/


All Articles