How to use the for loop in Django templates

What are Django templates?

According to the official docs, a Django template is a text document or a Python string marked-up using the Django template language. Templates are files, much like regular HTML documents, but with additional markup provided by the Django template language (DTL). This DTL is used to provide dynamic content to the webpage.

In this shot, we’ll be looking at how we can loop through a context array defined in the view to provide dynamic content, using the DTL.

Prerequisite: Basic Python and Django knowledge. To use the DTL, you first need to have a Django App and templates already set up. Learn how to do this here.

Using the for loop

Django, being based on Python, uses a similar for loop pattern with only minor differences in the syntax of the DTL.

Let’s imagine we have a context dictionary, defined in a view, which we want to loop through to be displayed in the template.

from django.shortcuts import render
# create a function
def home(request):
# create a dictionary
context = {
"data" : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
}
# return response
return render(request, "home.html", context)

As seen above in the views.py file, a home function or view is defined and contains the context dictionary we will loop through. It also points to our home.html template, where it will be rendered.

Navigate to your template, which in this case is our home.html example template below, where we will use the DTL for loop.

#for loop
{% for i in data %}
<div class="row">
{{ i }}
</div>
{% endfor %}

Upon observing the syntax of the DTL for loop, you will see it has a lot of similarities with regular Python syntax.

  • One difference is that the code is written between the DTL {% %} , which is the syntax used to inject dynamic data to the template.

  • Another difference is the presence of an {% endfor %} tag due to the absence of indentation, unlike regular Python syntax.

  • The for loop iterates over the context dictionary and renders the output to the template.

  • The additional div class declaration makes sure each iteration is printed on a new line.

Upon running your server, you’d get the following output on your webpage.

output on the browser
output on the browser

That’s it! Now you’re able to use the for loop in Django!

Free Resources