[Fixed]-How to display index during list iteration with Django?

43๐Ÿ‘

โœ…

You want the forloop.counter template variable.

The for loop sets a number of variables available within the loop:

forloop.counter The current iteration of the loop (1-indexed)

So your code would look like:

{% for sport in sports %}
    <p>{{forloop.counter}}. {{ sport }}</p>
{% endfor %}

Of course, for simply displaying the data as you do in your question, the easier way is just to show the items in an ordered list, and the browser will do the numbering for you:

<ol>
{% for sport in sports %}
    <li>{{ sport }}</li>
{% endfor %}
</ol>
๐Ÿ‘คnrabinowitz

4๐Ÿ‘

The answer from @nrabinowitz is a good solution if you want to use it in a template. But I think you were asking to do that from a view.

The best way to get the index and value from a list is using the enumerate function, like this:

>>> sports = ['football', 'basketball', 'soccer']
>>> for i,sport in enumerate(sports):
...     print "%d. %s" % (i, sport)
0. football
1. basketball
2. soccer

Or, if you want a 1-based index:

>>> for i,sport in enumerate(sports):
...     print "%d. %s" % (i+1, sport)
1. football
2. basketball
3. soccer
๐Ÿ‘คjuliomalegria

1๐Ÿ‘

courtesy of the answer above

If someone needs to use a condition of the loop iteration count, he can use this block of code.

2 is used for illustration of an integer.

{% if forloop.counter == 2 %}
do something what you want for second iteration
{% endfor %}
๐Ÿ‘คShamsul Arefin

Leave a comment