Django - iterate number in for loop of a template

325,989

Solution 1

Django provides it. You can use either:

  • {{ forloop.counter }} index starts at 1.
  • {{ forloop.counter0 }} index starts at 0.

In template, you can do:

{% for item in item_list %}
    {{ forloop.counter }} # starting index 1
    {{ forloop.counter0 }} # starting index 0

    # do your stuff
{% endfor %}

More info at: for | Built-in template tags and filters | Django documentation

Solution 2

Also one can use this:

{% if forloop.first %}

or

{% if forloop.last %}

Solution 3

{% for days in days_list %}
    <h2># Day {{ forloop.counter }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}

or if you want to start from 0

{% for days in days_list %}
        <h2># Day {{ forloop.counter0 }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}

Solution 4

from the docs https://docs.djangoproject.com/en/stable/ref/templates/builtins/#for you can found it to count items you can use a counter like this

{% for job in jobs %}
<td>{{ forloop.counter }}</td>
<td>{{ job.title }}</td>
<td>{{ job.job_url }}</td>
{% endfor %}
  • {{ forloop.counter }} start counting from 1
  • {{ forloop.counter0 }} start counting from 0

Solution 5

Do like this,

{% for days in days_list %}
    <h2># Day {{ forloop.counter }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}
Share:
325,989
orschiro
Author by

orschiro

Updated on August 23, 2022

Comments

  • orschiro
    orschiro over 1 year

    I have the following for loop in my django template displaying days. I wonder, whether it's possible to iterate a number (in the below case i) in a loop. Or do I have to store it in the database and then query it in form of days.day_number?

    {% for days in days_list %}
        <h2># Day {{ i }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
    {% endfor %}
    
  • VIKAS KOHLI
    VIKAS KOHLI over 7 years
    But it gives length-1.
  • Tim Woocker
    Tim Woocker about 6 years
    What about nested for loops? How can we tell django if we want to count the inner or the outer loop?
  • Rohan
    Rohan about 6 years
    @crey4fun, check forloop.parentloop refer docs for more info.
  • kontur
    kontur over 5 years
    Not the answer to the question, but still the answer for many people that will search for this question. Good stuff!
  • deps_stats
    deps_stats over 2 years
    I upvoted because it shows how to specifically answer the question. Although it is not a general ansswer, it gives an example on how to use it.