[django] Django - iterate number in for loop of a template

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 %}

This question is related to django for-loop django-templates

The answer is


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


[Django HTML template doesn't support index as of now], but you can achieve the goal:

If you use Dictionary inside Dictionary in views.py then iteration is possible using key as index. example:

{% for key, value in DictionartResult.items %} <!-- dictionartResult is a dictionary having key value pair-->
<tr align="center">
    <td  bgcolor="Blue"><a href={{value.ProjectName}}><b>{{value.ProjectName}}</b></a></td>
    <td> {{ value.atIndex0 }} </td>         <!-- atIndex0 is a key which will have its value , you can treat this key as index to resolve-->
    <td> {{ value.atIndex4 }} </td>
    <td> {{ value.atIndex2 }} </td>
</tr>
{% endfor %}

Elseif you use List inside dictionary then not only first and last iteration can be controlled, but all index can be controlled. example:

{% for key, value in DictionaryResult.items %}
    <tr align="center">
    {% for project_data in value %}
        {% if  forloop.counter <= 13 %}  <!-- Here you can control the iteration-->
            {% if forloop.first %}
                <td bgcolor="Blue"><a href={{project_data}}><b> {{ project_data }} </b></a></td> <!-- it will always refer to project_data[0]-->
            {% else %}
                <td> {{ project_data }} </td> <!-- it will refer to all items in project_data[] except at index [0]-->
            {% endif %}
            {% endif %}
    {% endfor %}
    </tr>
{% endfor %}

End If ;)

// Hope have covered the solution with Dictionary, List, HTML template, For Loop, Inner loop, If Else. Django HTML Documentaion for more methods: https://docs.djangoproject.com/en/2.2/ref/templates/builtins/


I think you could call the id, like this

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

{% 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 %}

Also one can use this:

{% if forloop.first %}

or

{% if forloop.last %}

Examples related to django

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip Pylint "unresolved import" error in Visual Studio Code Is it better to use path() or url() in urls.py for django 2.0? Unable to import path from django.urls Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?' ImportError: Couldn't import Django Django - Reverse for '' not found. '' is not a valid view function or pattern name Class has no objects member Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries How to switch Python versions in Terminal?

Examples related to for-loop

List append() in for loop Prime numbers between 1 to 100 in C Programming Language Get current index from foreach loop how to loop through each row of dataFrame in pyspark TypeScript for ... of with index / key? Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? Python for and if on one line R for loop skip to next iteration ifelse How to append rows in a pandas dataframe in a for loop? What is the difference between ( for... in ) and ( for... of ) statements?

Examples related to django-templates

Django - Did you forget to register or load this tag? How to add url parameters to Django template url tag? bootstrap 3 wrap text content within div for horizontal alignment Django, creating a custom 500/404 error page How can I get the username of the logged-in user in Django? Does Python have a toString() equivalent, and can I convert a db.Model element to String? How do I call a Django function on button click? What is the equivalent of "none" in django templates? Django - iterate number in for loop of a template Django -- Template tag in {% if %} block