简体   繁体   中英

Looping through a list/dictionary django template

my view.
teamname_list = team.objects.values('teamName')

in my template template html
{{teamname_list}}

outputs:
[{'teamName': "['Paul', 'John']"}]
---------------------------------------------------
alternatively values instead of values_list
view
teamname_list = team.objects.values('teamName')
in template
{{teamname_list}}
output:
[("['Paul', 'John']",)]

Is there any way to loop through teamname_list to get the characters individually so on the html page it shows as just Paul and John, treated as their own string or even producing a list so looping through them and adding them to an unordered list ie

* paul
* john

Been trying for a while now couple of hours and can't seem to get anything to work, tried every possible solution except for filters because I seem to be having a problem with using them. Any other solutions?

You can use a for loop in your django template. For example:

<ul>
  {% for teamname in teamname_list %}
    <li>{{ teamname }}</li>
  {% endfor %}
</ul>

EDIT: I didn't realize your list actually only has one value. Try doing this for starters:

teamname_list = team.objects.all()
teamname_list = team.objects.values_list('teamName', flat=True)

This will return list of names. Use one for loop in template and display names.

<ul>
  {% for teamname in teamname_list %}
    <li>*{{ teamname }}</li>
  {% endfor %}
</ul>
teamname_list = team.objects.all()

HTML code

<ul>
  {% for name in teamname_list %}
    <li>{{ name.teamName }}</li>
  {% endfor %}
</ul>

Please share your model for more clarification

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM