For Loop in Templates
A snippet showing how to loop over data with {% for %} in templates.
# models.py
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=80)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=150)
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="products")
price = models.DecimalField(max_digits=8, decimal_places=2)
def __str__(self):
return self.name
# admin.py
from django.contrib import admin
from .models import Category, Product
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
list_display = ("name",)
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_display = ("name", "category", "price")
# Result (Template loop)
# templates/product_list.html
<ul class="list-group">
{% for product in products %}
<li class="list-group-item d-flex justify-content-between">
<span>{{ forloop.counter }}. {{ product.name }} ({{ product.category.name }})</span>
<strong>{{ product.price }}</strong>
</li>
{% empty %}
<li class="list-group-item">No products available.</li>
{% endfor %}
</ul>
Explanation:
-
Use
{% for item in list %}to iterate;{% empty %}renders when the list is empty. -
Access loop metadata via
forloop(e.g.,forloop.counter,forloop.first). -
Use dot-lookup (e.g.,
product.category.name) to traverse relationships safely.
- Category Templates
- Total Views 767
- Last Modified 27 January, 2026
- Tags #templates #loops #iteration #context
Previous snippet
Template Inheritance with base.html
Next snippet