Open In App

for loop - Django Template Tags

Last Updated : 17 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Django templates allow you to render dynamic data by embedding Python-like logic into HTML. The for loop is one of the most commonly used template tags, enabling you to iterate over lists or other iterable objects. It helps you display repeated content (like lists, tables, etc.) in your templates without needing to write complex logic in the view.

Syntax of the for Tag

{% for item in iterable %}

<!-- Do something with 'item' -->

{% endfor %}

  • iterable: This is the collection (such as a list or a queryset) over which the loop will iterate.
  • item: This represents each individual element in the iterable during the iteration.

Example: For example, to display a list of athletes provided in athlete_list:

HTML
<ul> 
{% for athlete in athlete_list %} 
	<li>{{ athlete.name }}</li> 
{% endfor %} 
</ul> 

Example of "for loop" - Django Template Tags

Illustration of How to use "for tag" in Django templates using an example. Consider a project named "geeksforgeeks" having an app named geeks.

Refer to the following articles to check how to create a project and an app in Django.

View (geeks/views.py)

Python
# import Http Response from django 
from django.shortcuts import render 

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

URL Configuration (geeks/urls.py)

Python
from django.urls import path 

# importing views from views.py 
from .views import geeks_view 

urlpatterns = [ 
	path('', geeks_view), 
] 

Template (templates/geeks.html)

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

Output

cycle-django-template-tags
for loop - Django Template

Advanced Usage

One can loop over a list in reverse by using {% for obj in list reversed %}.

If you need to loop over a list of lists, you can unpack the values in each sublist into individual variables. For example, if your context contains a list of (x, y) coordinates called points, you could use the following to output the list of points:

HTML
{% for x, y in points %}
    There is a point at {{ x }}, {{ y }}
{% endfor %}

Example:

If your context is:

points = [(1, 2), (3, 4), (5, 6)]

Output:

There is a point at 1, 2
There is a point at 3, 4
There is a point at 5, 6

This can also be useful if you need to access the items in a dictionary. For example, if your context contained a dictionary data, the following would display the keys and values of the dictionary:

HTML
{% for key, value in data.items %}
    {{ key }}: {{ value }}
{% endfor %}


Example:

If your context is:

data = {'name': 'Alice', 'age': 30, 'city': 'Paris'}

Output:

name: Alice
age: 30
city: Paris

Next Article
Practice Tags :

Similar Reads