Django For Loop

Iterate through data in Django templates

🔁 What is Django For Loop?

Django for loops iterate through lists, tuples, and querysets in templates. Loop through data collections to display repeated content dynamically, making it easy to render multiple items efficiently.


<!-- Basic for loop -->
{% for item in items %}
    <p>{{ item }}</p>
{% endfor %}
                                    

Loop Features

📋

Basic Loop

Iterate through lists and arrays

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

Loop Counter

Track iteration number

{{ forloop.counter }}
🔄

Reversed Loop

Iterate in reverse order

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

Empty Loop

Handle empty lists gracefully

{% empty %}
  No items
{% endfor %}

🔹 Simple For Loop

The basic for loop iterates through a list or queryset and displays each item. This is the most common way to render multiple items in Django templates.

🔸 View

def fruits(request):
    context = {
        'fruits': ['Apple', 'Banana', 'Orange', 'Mango', 'Grapes']
    }
    return render(request, 'fruits.html', context)

🔸 Template

<h2>Fruit List</h2>
<ul>
    {% for fruit in fruits %}
        <li>{{ fruit }}</li>
    {% endfor %}
</ul>

Output:

Fruit List

  • Apple
  • Banana
  • Orange
  • Mango
  • Grapes

🔹 Loop Counter Variables

Django provides special variables inside for loops to track iteration state. These forloop variables help you create numbered lists, alternate styles, and handle first or last items.

<table>
    {% for item in items %}
        <tr>
            <td>{{ forloop.counter }}</td>
            <td>{{ item }}</td>
            <td>
                {% if forloop.first %}First{% endif %}
                {% if forloop.last %}Last{% endif %}
            </td>
        </tr>
    {% endfor %}
</table>

Available forloop variables:

  • forloop.counter - Current iteration (1-indexed)
  • forloop.counter0 - Current iteration (0-indexed)
  • forloop.first - True if first iteration
  • forloop.last - True if last iteration
  • forloop.revcounter - Iterations remaining (1-indexed)

🔹 Looping Through Dictionaries

Loop through dictionary items to access both keys and values. Django makes it easy to iterate over dictionaries and display structured data in your templates.

🔸 View

def student(request):
    context = {
        'student': {
            'name': 'John Doe',
            'age': 20,
            'grade': 'A',
            'email': '[email protected]'
        }
    }
    return render(request, 'student.html', context)

🔸 Template

<h2>Student Information</h2>
<table>
    {% for key, value in student.items %}
        <tr>
            <td><strong>{{ key|title }}:</strong></td>
            <td>{{ value }}</td>
        </tr>
    {% endfor %}
</table>

Output:

Student Information

Name: John Doe
Age: 20
Grade: A
Email: [email protected]

🔹 Empty Tag

The empty tag handles cases when a list is empty. Display alternative content when there are no items to loop through, providing better user experience.

🔸 View

def products(request):
    context = {
        'products': []  # Empty list
    }
    return render(request, 'products.html', context)

🔸 Template

<h2>Products</h2>
<ul>
    {% for product in products %}
        <li>{{ product.name }} - ${{ product.price }}</li>
    {% empty %}
        <li>No products available at the moment.</li>
    {% endfor %}
</ul>

Output:

Products

  • No products available at the moment.

🔹 Reversed Loop

Use the reversed keyword to iterate through a list in reverse order. This is useful for displaying items from newest to oldest or in descending order.

<h2>Countdown</h2>
<ul>
    {% for num in numbers reversed %}
        <li>{{ num }}</li>
    {% endfor %}
</ul>

Output (if numbers = [1, 2, 3, 4, 5]):

Countdown

  • 5
  • 4
  • 3
  • 2
  • 1

🔹 Nested Loops

Django supports nested for loops for multi-dimensional data structures. Loop through lists within lists to display complex hierarchical data like categories with items.

🔸 View

def categories(request):
    context = {
        'categories': [
            {'name': 'Fruits', 'items': ['Apple', 'Banana']},
            {'name': 'Vegetables', 'items': ['Carrot', 'Broccoli']}
        ]
    }
    return render(request, 'categories.html', context)

🔸 Template

{% for category in categories %}
    <h3>{{ category.name }}</h3>
    <ul>
        {% for item in category.items %}
            <li>{{ item }}</li>
        {% endfor %}
    </ul>
{% endfor %}

Output:

Fruits

  • Apple
  • Banana

Vegetables

  • Carrot
  • Broccoli

💡 Important Tips:

  • Always close for loops with {% endfor %}
  • Use {% empty %} to handle empty lists gracefully
  • Access loop variables with forloop.counter , forloop.first , etc.
  • Use reversed keyword to iterate in reverse order
  • Nested loops are supported for complex data structures

🧠 Test Your Knowledge

Which variable gives you the current iteration number starting from 1?