Django for loop

In this Django tutorial, we will learn about the Django for loop. Here we will learn how to use a for loop in Django. And we will also discuss different examples related to having a for loop in Django. These are the following topics that we are going to discuss in this tutorial.

  • Django for loop
  • Django for loop in html
  • Django for loop counter
  • Django for loop range
  • Django for loop in html table
  • Django for loop in template
  • Django for loop last item
  • Django for loop first item
  • Django for loop break
  • Django for loop not working
  • Django for loop model objects

Django for loop

Before understanding how to create and use a for loop in Django, we should know what is a for loop.

A loop is a control statement used to execute one or more than one statement multiple times. Now, in python, there are different types of loops from which one is for loop.

In python, a for loop is used to iterate over some sequence, and it is basically used to take each item one after another. In python, we can use a for loop to iterate either a string, dictionary, list, tuple, or set. And here is the general syntax of using for loop in python.

for iterating_var in sequence:
   statements(s)

For more details related to for loop in python, you can read the following tutorial.

Now, we can use the for loop in the views.py file in the same way as we use it in python. But in Django, there is one more efficient way to use the for loop for iterating over some values. And that way is by using for template tag in our Django template.

Django for loop in template

To create and use for loop in Django, we generally use the “for” template tag. This tag helps to loop over the items in the given array, and the item is made available in the context variable.

The syntax of using the “for” tag in a template is shown below.

{% for i in list %}

{% endfor %}

Now, let’s take an example to understand the use of this for tag in the template. And for this demonstration, we will display the list of employees using for loop.

So, first, we will use the views.py file to fetch all the objects from the Employee model. And then, we will send them as a context variable to the home.html page. Here is the code that we have added to our views.py file.


from django.shortcuts import render
from myApp.models import Employee

def home(request):
   employee_list = Employee.objects.all()
   return render(request, 'home.html', {'employee_list': employee_list})

Next, we will use the urls.py file to map a URL to the home view, and for this, we have added the following code in the file.

from django.urls import path
from . import views

urlpatterns = [
   path('home/', views.home, name='home')
]

So, the next step is to create a home.html page in your template directory. And in the home.html page, we will use the “for” tag to iterate over the context variable. And from the context variable, we will try to get the employee name in a list.

Here is the code of our home.html page.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <title>Python Guides</title>
</head>

<body>
    <br>
    <div class="container w-50">
        <ul class="list-group">
            <li class="list-group-item active text-center font-weight-bold">Employee List</li>
        {% for employee in employee_list %}
            <li class="list-group-item text-center">{{ employee.name }}</li>
        {% endfor %}
        </ul>
    </div>
</body>
</html>

Now, it’s time to see the output of the above example implementation. For this, we need to run the development server and open the home page.

Django for loop in template
Home Page

Read: Python Django vs Flask

Django for loop counter

Now, Django also provides multiple built-in variables that we can use while using the for loop tag. And the majority of them are used to get a counter while using the for loop.

So, by using those variables, we can get different types of the counter. All the variables related to the counter are listed below.

  • forloop.counter: By using this, the iteration of the loop starts from index 1.
  • forloop.counter0: By using this, the iteration of the loop starts from index 0.
  • forloop.revcounter: By using this, the iteration starts from the end of the loop till index 1.
  • forloop.revcounter0: By using this, the iteration starts from the end of the loop till index 0.

Now, for demonstration, let’s use one of these variables in our previous Employee list example. As you can see in the output of our previous example, we don’t have an index in our employee list.

So, we will use the “forloop.counter” variable to add an index to our employee list. And this time, we only need to modify our home.html page.

The complete code that we have added to our home.html page is given below.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <title>Python Guides</title>
</head>

<body>
    <br>
    <div class="container w-50">
        <ul class="list-group">
            <li class="list-group-item active text-center font-weight-bold">Employee List</li>
            {% for employee in employee_list %}
            <li class="list-group-item">{{ forloop.counter }}. {{ employee.name }}</li>
            {% endfor %}
        </ul>
    </div>
</body>
</html>

On the home.html page, we are using the for loop variable in the for loop. And it will add an index value for each employee name that is there in the list. The final result is shown in the image below.

Django for loop counter
Final Result

Read: How to install Django

Django for loop last item

Django also provides a built-in variable with the for loop tag, using which we can determine the last item from the array.

And the name of the variable is “forloop.last“. This variable returns True for the last item of the array, and for all other items, it returns False.

So, we can easily use this variable to fetch the last value from the array. But first, let’s see how this variable returns the True/False values for each item in the array.

Again, for this demonstration, we will use the same employee list example from the first section. And we will use the variable in the for loop of the home.html page.

So, we have only made some changes to the body of the page. And the code for the body of the home.html page is as follows.

<body>
    <br>
    <div class="container w-50">
        <ul class="list-group">
            <li class="list-group-item active text-center font-weight-bold">Employee List</li>
            {% for employee in employee_list %}
            <li class="list-group-item"><b>{{ forloop.last }}</b>- {{ employee.name }}</li>
            {% endfor %}
        </ul>
    </div>
</body>

Now, let’s check the result by starting the development server and moving to the home page.

Django for loop last item
home.html page

Now, from the above output, we can see that the variable has returned True only for the last item. And for all other items, it has returned False.

Now, to only fetch the last item from the array, we need to use the IF statement in the template.

Here is the modified code that we are going to use.

<body>
    <br>
    <div class="container w-50">
        <ul class="list-group">
            <li class="list-group-item active text-center font-weight-bold">Last Name From Employee List</li>
            {% for employee in employee_list %}
            {% if forloop.last %}
            <li class="list-group-item text-center">{{ employee.name }}</li>
            {% endif %}
            {% endfor %}
        </ul>
    </div>
</body>

In the above code, we have specified an IF block with forloop.last variable. So, the loop will only fetch the last name from the object array. As the variable will only return True for the last item. In the end, we will get the following output.

Using for loop in Django to get last item
Final Result

Read: How to setup Django project

Django for loop first item

Similar to selecting the last item, we also have a variable to fetch the first item from the given array. The name of the variable is forloop.first and it can only be used within the for loop.

And returns True only for the first item in the array. And for all other items in the array, it returns False.

Let’s first see how this variable returns the True/False values while looping through each item in the array. For this, we will continue using the same employee list example from the first section.

And here is the code of the home.html file where we are using this variable.

<body>
    <br>
    <div class="container w-50">
        <ul class="list-group">
            <li class="list-group-item active text-center font-weight-bold">Employee List</li>
            {% for employee in employee_list %}
            <li class="list-group-item"><b>{{ forloop.first }}</b>- {{ employee.name }}</li>
            {% endfor %}
        </ul>
    </div>
</body>

The output of this home.html page is shown in the image below.

Django for loop first item
home.html page

Now, from the above output, we can see that the variable has returned True only for the first item. And for all other items, it has returned False.

Now, to only fetch the first item from the array, we need to use the IF statement in the template. Here is the modified code that we are going to use.

<body>
    <br>
    <div class="container w-50">
        <ul class="list-group">
            <li class="list-group-item active text-center font-weight-bold">First Name From Employee List</li>
            {% for employee in employee_list %}
            {% if forloop.first %}
            <li class="list-group-item text-center">{{ employee.name }}</li>
            {% endif %}
            {% endfor %}
        </ul>
    </div>
</body>

In the above code, we have specified an IF block with forloop.first variable. So, the loop will only fetch the first name from the object array. As the variable will only return True for the first item. In the end, we will get the following output.

Using for loop in Django to get first item
Final Result

Read: Python Django get admin password

Django for loop range

While working on the logic of our application, we might need to run a loop N number of times. To implement this task in python, we simply use the range() function in the for loop.

The range() function is used to return a series of numbers that starts at 0 and increments by 1 (by default) before stopping at a specified value.

But in Django, there is no range tag or function that we can use in our template to implement this task. But don’t worry, still, there is 1 way through which we can run a loop N number of times. And we will discuss that method in this section.

Alternative Method

In this method, first, we will create a view where we will use the range() function to get a list of numbers. And then, we will pass the list to the render function along with the template.

Let’s understand this method with the help of an example, and for this, we will display the square of numbers from 1 to 10. So, first, we create a view in our views.py file, and the code for this is given below.

from django.shortcuts import render

def home(request):
   return render(request, 'home.html', {'range': range(1,11)})

In the above code, we are simply using the range() function to get a list of numbers from 1 to 10. And we are simply passing the list in the render function with the template.

Next, we will add the following code in the body of the home.html page.

<body>
    <br>
    <div class="container w-50">
        <ul class="list-group">
            <li class="list-group-item active text-center font-weight-bold">Square of values</li>
            {% for x in range %}
            <li class="list-group-item text-center">Square of {{x}} is {% widthratio x 1 x %}</li>
            {% endfor %}
        </ul>
    </div>
</body>

Now, on this page, we are using the for loop to get one value at a time from the list. And then, we are using the single value to get the square of it. To get the square, we are using a widthradio filter, and in the filter, (x 1 x) simply means (x * x).

Here is the final result of the above example.

Django for loop range
Final Result

Read: Difference between app and project in Django

Django for loop break

In python, the break statement is used to eliminate the execution of the current loop and start the execution of the next statement. A break statement in python can be used in both for and while loops.

Unfortunately, the Django template doesn’t support the use of a break statement. To achieve the functionality of a break statement, we can use the IFELSE statement within the for loop to limit the result.

Let’s understand this with the help of an example and for this, we will use the Employee model and its data. And we will try to list only 5 employee names from the model. So, we are using the same code in the views.py file as shown in the starting section.

Next, we add for loop in our home.html page, and in the loop, we will use an IF block. The code for the home.html page is given below.

<body>
    <br>
    <div class="container w-50">
        <ul class="list-group">
            <li class="list-group-item active text-center font-weight-bold">Employee List</li>
            {% for employee in employee_list %}
            {% if forloop.counter <= 5 %}
            <li class="list-group-item">{{ forloop.counter }}. {{ employee.name }}</li>
            {% endif %}
            {% endfor %}
        </ul>
    </div>
</body>

In the above code, first, we are using the for loop to iterate over the list of employees. After this, we are using the IF statement to check if the index for an employee’s name is less than or equal to 5. In the ens, we will get the following result as an output.

Django for loop break
Final Result

Read: How to Create model in Django

Django for loop in html table

Till now, we were only using the for loop in our template to get the result in a list and we were also using only one value from the set of objects.

Now, in this section, we will understand how to use a for loop to iterate over multiple values from the array of objects. And we will also understand how to arrange the values in an HTML table using for loop.

Let’s understand this implementation with the help of an example and for this, again we will use the Employee model. And we will use the for loop to iterate over the array of objects and display the employee details in a table.

First, we will create a view to fetch all the objects from the Employee model, and then, we will pass it in the render function with the template. The code for views.py is given below.

from django.shortcuts import render
from myApp.models import Employee

def home(request):
   employee_list = Employee.objects.all()
   return render(request, 'home.html', {'employee_list': employee_list})

Next, we will create the home.html file and we will use the for loop. Here is the code for the HTML file.

<body>
    <br>
    <div class="container-fluid">
        <table class="table">
            <thead class="thead-dark">
                <tr>
                    <th scope="col">#</th>
                    <th scope="col">Employee Name</th>
                    <th scope="col">Job Title</th>
                    <th scope="col">Joining Date</th>
                </tr>
            </thead>
            <tbody>
                {% for employee in employee_list %}
                <tr>
                    <th scope="row">{{ forloop.counter }}</th>
                    <td>{{ employee.name }}</td>
                    <td>{{ employee.job_title }}</td>
                    <td>{{ employee.joining_date }}</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
</body>

In the above code, we are using the for loop within the <body> tag and after this, we have specified the values within the <td> tag. Here is the result of the above example.

Django for loop in html table
Home page

Read: How to Get Current time in Django

Django for loop not working

A for loop is a conditional statement used to iterate over some set pf values sequentially. And here is the general syntax of using for loop in python.

for iterating_var in sequence:
   statements(s)

Now, we can use the for loop in the view in the same way as we use it in python. But, what if we want to use the for loop in our templates.

Now, if we use the same syntax in our template then, the for loop will not work. Django templates do not work in the way python does.

To use the for loop in our template pages, we have to the “for” template tag and the syntax of using it is as follows.

{% for i in list %}

{% endfor %}

Now, we have already demonstrated many examples related to using the “for” template tag.

In python, we can use a for loop to iterate either a string, dictionary, list, tuple, or set. But in the case of Django, most of the time we have to iterate over the table data.

And in Django, data in a table is store in form of python objects. So to access them, we have to iterate over the array of objects and understand how to fetch values from that objects.

And we have also explained multiple examples related to that in this article.

Read: Python Django filter

Django for loop in html

Django generates HTML dynamically using templates and we can use these templates to display static as well as dynamic HTML content.

Django uses its template system, which uses the Django template language. So, Django uses the Django template language or DTL template to display dynamic data created by Python and Django into HTML.

Now, to use the for loop in these Django templates, we need to use the for template tag. And we have already explained its usability in the first section of this article.

In this Django tutorial, we learned about the Django for loop. Here we have discussed how to use a for loop in Django. And we have also discussed different examples related to having a for loop in Django. These are the following topics that we have discussed in this tutorial.

  • Django for loop
  • Django for loop in html
  • Django for loop counter
  • Django for loop range
  • Django for loop in html table
  • Django for loop in template
  • Django for loop last item
  • Django for loop first item
  • Django for loop break
  • Django for loop not working
  • Django for loop model objects