How to Use For Loop in Django Template: Syntax and Examples
In Django templates, use the
{% for item in list %}...{% endfor %} tag to loop over items in a list or queryset. Inside the loop, you can access each item and display its properties or values.Syntax
The Django template for loop uses the syntax {% for item in list %}...{% endfor %}. Here, item is a variable name you choose to represent each element, and list is the list or queryset you want to loop over.
- {% for item in list %}: Starts the loop, assigning each element to
item. - Loop body: Template code that runs for each
item. - {% endfor %}: Ends the loop.
django
{% for item in list %}
{{ item }}
{% endfor %}Example
This example shows how to loop over a list of fruits and display each fruit name in an unordered list.
django
{% comment %} Template file: fruits.html {% endcomment %}
<ul>
{% for fruit in fruits %}
<li>{{ fruit }}</li>
{% endfor %}
</ul>Output
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
</ul>
Common Pitfalls
Common mistakes when using for loops in Django templates include:
- Forgetting the
{% endfor %}tag, which causes template errors. - Using a variable name in the loop that conflicts with other variables.
- Trying to modify the list inside the template (templates are for display only).
- Not passing the list or queryset to the template context from the view.
django
{% comment %} Wrong: Missing endfor {% endcomment %}
<ul>
{% for fruit in fruits %}
<li>{{ fruit }}</li>
<!-- Missing {% endfor %} here -->
</ul>
{% comment %} Right: Properly closed loop {% endcomment %}
<ul>
{% for fruit in fruits %}
<li>{{ fruit }}</li>
{% endfor %}
</ul>Quick Reference
Tips for using for loops in Django templates:
- Use
{% for item in list %}to start and{% endfor %}to end. - Access the current item with
{{ item }}. - Use
forloop.counterfor the current loop index (starting at 1). - Use
{% empty %}block to handle empty lists:{% empty %}No items found.{% endfor %}.
Key Takeaways
Use {% for item in list %}...{% endfor %} to loop over lists in Django templates.
Always close the loop with {% endfor %} to avoid template errors.
Access the current item inside the loop with {{ item }}.
Use forloop.counter to get the current iteration number starting at 1.
Use the {% empty %} tag inside the loop to handle empty lists gracefully.