Django For Loop

I’ve worked on numerous web projects using Django. One of the most common tasks I encounter is displaying lists or collections of data dynamically in templates. Django’s template language provides a powerful and simple way to do this using the for loop.

If you’re new to Django or want to deepen your understanding of how to use the for loop in Django templates, you’re in the right place. In this article, I’ll share practical insights and examples drawn from real-world projects, including some tailored for US-based applications.

Let’s get in!

What is the Django For Loop?

In Django templates, the for loop allows you to iterate over lists, querysets, or any iterable data passed from your views. This is essential when you want to display multiple items, such as a list of users, products, or events.

Unlike Python’s for loop, Django’s for loop is used within the HTML template to render dynamic content.

Read Check if Python Dictionary is Empty

Basic Syntax of Django For Loop

Here’s the simple syntax you’ll use inside your Django template:

{% for item in list %}
    {{ item }}
{% endfor %}

This loop goes through each element in list and renders it.

Example: Display a List of US States

Imagine you have a Django project where you want to display a list of US states on a webpage. Here’s how you can do it.

Step 1: Define Your View

In your Django app’s views.py create a view that passes a list of US states to the template.

from django.shortcuts import render

def states_list(request):
    us_states = [
        'California', 'Texas', 'Florida', 'New York', 'Illinois',
        'Pennsylvania', 'Ohio', 'Georgia', 'North Carolina', 'Michigan'
    ]
    return render(request, 'states.html', {'states': us_states})

Step 2: Create the Template

In your templates folder, create a file named states.html with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>List of US States</title>
</head>
<body>
    <h1>Top 10 US States</h1>
    <ul>
        {% for state in states %}
            <li>{{ forloop.counter }}. {{ state }}</li>
        {% endfor %}
    </ul>
</body>
</html>

Notice the use of {{ forloop.counter }} — this is a special Django template variable that gives you the current iteration count, starting from 1.

Step 3: Configure URL

Add a URL pattern in your urls.py:

from django.urls import path
from .views import states_list

urlpatterns = [
    path('states/', states_list, name='states_list'),
]

I executed the above example code and added the screenshot below.

django for loop

What Happens Here?

When you navigate to /states/, Django renders the states.html template and loops through the states list, displaying each state with its corresponding number.

Check out Python Filter Not in Django

Advanced Usage of Django For Loop

Now, I will explain to you the advanced usage of Django for loops.

Accessing Loop Variables

Django provides several useful variables inside the for loop:

  • forloop.counter — Current iteration (1-based)
  • forloop.counter0 — Current iteration (0-based)
  • forloop.first — True if first iteration
  • forloop.last — True if last iteration
  • forloop.parentloop — Access the parent loop if nested

These variables help you customize output conditionally.

Example: Highlight First and Last States

Modify the template to highlight the first and last states:

<ul>
    {% for state in states %}
        <li>
            {% if forloop.first %}
                <strong>First: {{ state }}</strong>
            {% elif forloop.last %}
                <strong>Last: {{ state }}</strong>
            {% else %}
                {{ state }}
            {% endif %}
        </li>
    {% endfor %}
</ul>

Read Union Operation on Django Models

Using Django For Loop with QuerySets

In real projects, you often work with data from databases. Django’s ORM returns QuerySets which are iterable, so you can use the for loop the same way.

Example: Displaying US Cities from Database

Assuming you have a model City with fields name and state, and you want to display cities in California.

# models.py
from django.db import models

class City(models.Model):
    name = models.CharField(max_length=100)
    state = models.CharField(max_length=100)

    def __str__(self):
        return self.name
# views.py
from django.shortcuts import render
from .models import City

def california_cities(request):
    cities = City.objects.filter(state='California')
    return render(request, 'cities.html', {'cities': cities})
<!-- cities.html -->
<h1>Cities in California</h1>
<ul>
    {% for city in cities %}
        <li>{{ city.name }}</li>
    {% empty %}
        <li>No cities found.</li>
    {% endfor %}
</ul>

I executed the above example code and added the screenshot below.

django template for loop

Here, the {% empty %} tag handles the case where the queryset is empty, a handy feature to improve user experience.

Check out Create a model in Django

Nested For Loops in Django Templates

Sometimes, you might need to loop through nested data structures.

Example: States and Their Major Cities

Suppose you have a dictionary in your view:

def states_and_cities(request):
    data = {
        'California': ['Los Angeles', 'San Francisco', 'San Diego'],
        'Texas': ['Houston', 'Dallas', 'Austin'],
        'Florida': ['Miami', 'Orlando', 'Tampa']
    }
    return render(request, 'states_cities.html', {'data': data})

Template:

<h1>States and Their Major Cities</h1>
<ul>
    {% for state, cities in data.items %}
        <li><strong>{{ state }}</strong>
            <ul>
                {% for city in cities %}
                    <li>{{ city }}</li>
                {% endfor %}
            </ul>
        </li>
    {% endfor %}
</ul>

This nested loop displays each state and its cities cleanly.

Read ModuleNotFoundError: No module named Django

Filtering Data Before Looping

Django templates are intentionally limited and don’t support complex logic like filtering inside templates.

I recommend filtering or processing data in views before passing it to templates. This keeps templates clean and maintainable.

The Django for loop is a simple yet powerful tool to render dynamic lists in your web pages. Whether you’re iterating over Python lists, QuerySets, or nested data, the for loop combined with built-in variables like forloop.counter gives you the flexibility to customize your output.

Remember to handle empty data gracefully using the {% empty %} tag and keep your templates focused on presentation by doing data processing in views.

I hope this guide helps you confidently use Django for loops in your projects, especially when working with US-centric data like states and cities.

If you have any questions or want to share your experience, feel free to leave a comment below!

Other Django Articles You May Like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.