How to Use Filter in Django Template: Syntax and Examples
In Django templates, you use the
filter tag inside a {% for %} loop combined with an if condition to display only items that meet certain criteria. Django templates do not have a built-in filter function like Python, so filtering is done with conditional statements inside loops.Syntax
The Django template language does not have a direct filter function like Python. Instead, you filter items by looping over a list with {% for %} and using {% if %} inside the loop to check conditions.
Basic pattern:
{% for item in list %}
{% if item.property == value %}
{{ item }}
{% endif %}
{% endfor %}This means: for each item in list, show it only if it meets the condition.
django
{% for item in list %}
{% if item.property == value %}
{{ item }}
{% endif %}
{% endfor %}Example
This example shows how to display only users who are active from a list passed to the template as users. Each user has an is_active property.
django
{% for user in users %}
{% if user.is_active %}
<p>{{ user.username }} is active.</p>
{% endif %}
{% endfor %}Output
<p>alice is active.</p>
<p>charlie is active.</p>
Common Pitfalls
Many beginners expect Django templates to support Python-like filter() functions directly, but templates only support simple logic. Trying to filter a list outside a loop or using Python syntax will not work.
Also, complex filtering logic should be done in the view, not the template, to keep templates simple and fast.
django
{# Wrong: Trying Python filter syntax in template #}
{# {% filter user.is_active for user in users %} #} {# This will cause an error #}
{# Right: Use if inside for loop #}
{% for user in users %}
{% if user.is_active %}
{{ user.username }}
{% endif %}
{% endfor %}Quick Reference
| Usage | Description |
|---|---|
| {% for item in list %} {% if condition %} ... {% endif %} {% endfor %} | Loop over list and show items meeting condition |
| {{ variable|lower }} | Use built-in filters to transform output (not for filtering lists) |
| Filter data in views | Do complex filtering in Python views, not templates |
Key Takeaways
Django templates filter lists by combining {% for %} loops with {% if %} conditions.
There is no direct filter function in Django templates like in Python.
Do complex filtering in views to keep templates simple and efficient.
Use built-in template filters for formatting, not for filtering lists.
Always test your conditions inside loops to avoid errors.