Django Filter Reference

Transform and format template variables with filters

🔧 What are Template Filters?

Template filters modify variables in Django templates using the pipe symbol. They transform data for display, format text, perform calculations, and manipulate strings without changing the original data in your database.


<!-- Basic filter usage -->
{{ name|lower }}
{{ price|floatformat:2 }}
{{ text|truncatewords:10 }}
                                    

Common Filters

🔤

String Filters

Transform text and strings

{{ text|upper }}
{{ text|lower }}
{{ text|title }}
🔢

Number Filters

Format numbers and math

{{ value|add:5 }}
{{ price|floatformat:2 }}
{{ num|divisibleby:3 }}
📅

Date Filters

Format dates and times

{{ date|date:"Y-m-d" }}
{{ time|time:"H:i" }}
{{ date|timesince }}
📋

List Filters

Manipulate lists and sequences

{{ items|length }}
{{ list|first }}
{{ list|join:", " }}

🔹 String Filters

String filters transform text case, truncate content, and manipulate string values for better display and formatting in templates.

<!-- Case transformation -->
{{ "hello world"|upper }}  <!-- HELLO WORLD -->
{{ "HELLO WORLD"|lower }}  <!-- hello world -->
{{ "hello world"|title }}  <!-- Hello World -->
{{ "hello world"|capfirst }}  <!-- Hello world -->

<!-- Truncate text -->
{{ "This is a long sentence"|truncatewords:3 }}
<!-- Output: This is a... -->

{{ "Hello World"|truncatechars:8 }}
<!-- Output: Hello... -->

<!-- String manipulation -->
{{ "  spaces  "|striptags }}  <!-- Remove HTML tags -->
{{ "hello"|ljust:10 }}  <!-- Left justify -->
{{ "hello"|rjust:10 }}  <!-- Right justify -->
{{ "hello"|center:10 }}  <!-- Center text -->

Output Examples:

HELLO WORLD

hello world

Hello World

This is a...

🔹 Number Filters

Number filters perform mathematical operations, format decimal places, and display numbers in human-readable formats like currency and percentages.

<!-- Math operations -->
{{ 10|add:5 }}  <!-- 15 -->
{{ 10|add:-3 }}  <!-- 7 -->

<!-- Float formatting -->
{{ 3.14159|floatformat }}  <!-- 3 -->
{{ 3.14159|floatformat:2 }}  <!-- 3.14 -->
{{ 3.1|floatformat:2 }}  <!-- 3.10 -->

<!-- Divisibility check -->
{% if value|divisibleby:2 %}
    <p>Even number</p>
{% endif %}

<!-- File size formatting -->
{{ 123456789|filesizeformat }}  <!-- 117.7 MB -->

<!-- Phone number formatting -->
{{ "1234567890"|phone2numeric }}  <!-- Format phone -->

Output Examples:

15

3.14

117.7 MB

🔹 Date and Time Filters

Date filters format datetime objects into readable strings, calculate time differences, and display relative time like "2 hours ago" or "in 3 days".

<!-- Date formatting -->
{{ post.created_at|date:"Y-m-d" }}  <!-- 2024-01-15 -->
{{ post.created_at|date:"F j, Y" }}  <!-- January 15, 2024 -->
{{ post.created_at|date:"D, M j" }}  <!-- Mon, Jan 15 -->

<!-- Time formatting -->
{{ event.time|time:"H:i" }}  <!-- 14:30 -->
{{ event.time|time:"g:i A" }}  <!-- 2:30 PM -->

<!-- Relative time -->
{{ post.created_at|timesince }}  <!-- 2 hours, 30 minutes -->
{{ post.created_at|timesince:now }}  <!-- Time since now -->
{{ future_date|timeuntil }}  <!-- 3 days, 5 hours -->

<!-- Natural day -->
{{ date|naturalday }}  <!-- today, yesterday, tomorrow -->

<!-- Natural time -->
{% load humanize %}
{{ date|naturaltime }}  <!-- 2 hours ago -->

Output Examples:

2024-01-15

January 15, 2024

2:30 PM

2 hours ago

🔹 List and Sequence Filters

List filters work with sequences to get length, join items, slice ranges, and access first or last elements from lists and querysets.

<!-- List length -->
{{ items|length }}  <!-- 5 -->

<!-- First and last -->
{{ items|first }}  <!-- First item -->
{{ items|last }}  <!-- Last item -->

<!-- Join list items -->
{{ tags|join:", " }}  <!-- python, django, web -->
{{ names|join:" and " }}  <!-- Alice and Bob and Charlie -->

<!-- Slice list -->
{{ items|slice:":3" }}  <!-- First 3 items -->
{{ items|slice:"2:" }}  <!-- From index 2 onwards -->

<!-- Random item -->
{{ items|random }}  <!-- Random item from list -->

<!-- Make list -->
{{ "abc"|make_list }}  <!-- ['a', 'b', 'c'] -->

Output Examples:

5

python, django, web

Alice and Bob and Charlie

🔹 URL and Link Filters

URL filters encode URLs, convert text to links, and escape special characters for safe use in web addresses and HTML attributes.

<!-- URL encoding -->
{{ "hello world"|urlencode }}  <!-- hello%20world -->
{{ "name=John&age=30"|urlencode }}  <!-- name%3DJohn%26age%3D30 -->

<!-- Convert URLs to links -->
{{ text|urlize }}  <!-- Converts URLs to clickable links -->
{{ text|urlizetrunc:15 }}  <!-- Truncate long URLs -->

<!-- Escape HTML -->
{{ html_content|escape }}  <!-- Escape HTML characters -->
{{ html_content|force_escape }}  <!-- Force escape -->

<!-- Safe HTML -->
{{ trusted_html|safe }}  <!-- Mark as safe (use carefully) -->
<!-- Example usage -->
<a href="/search/?q={{ query|urlencode }}">Search</a>

<p>{{ user_comment|escape }}</p>

<div>{{ blog_content|safe }}</div>

🔹 Default and Conditional Filters

Default filters provide fallback values for empty or missing variables, handle None values, and display alternative content when data is unavailable.

<!-- Default value -->
{{ value|default:"N/A" }}  <!-- Show N/A if value is empty -->
{{ name|default:"Anonymous" }}  <!-- Default name -->

<!-- Default if None -->
{{ value|default_if_none:"Not set" }}  <!-- Only if None -->

<!-- Yes/No for boolean -->
{{ is_active|yesno:"Yes,No,Maybe" }}  <!-- True/False/None -->
{{ is_published|yesno:"Published,Draft" }}

<!-- Pluralize -->
{{ count }} item{{ count|pluralize }}  <!-- 1 item, 2 items -->
{{ count }} categor{{ count|pluralize:"y,ies" }}  <!-- category/categories -->

Output Examples:

N/A

Anonymous

1 item

5 items

🔹 Humanize Filters

Humanize filters make data more readable by adding commas to numbers, converting integers to words, and formatting values in natural language.

<!-- Load humanize library -->
{% load humanize %}

<!-- Add commas to numbers -->
{{ 1000000|intcomma }}  <!-- 1,000,000 -->
{{ 5000.50|intcomma }}  <!-- 5,000.50 -->

<!-- Integer to words -->
{{ 1|apnumber }}  <!-- one -->
{{ 5|apnumber }}  <!-- five -->
{{ 15|apnumber }}  <!-- 15 -->

<!-- Ordinal numbers -->
{{ 1|ordinal }}  <!-- 1st -->
{{ 2|ordinal }}  <!-- 2nd -->
{{ 3|ordinal }}  <!-- 3rd -->

<!-- Natural integers -->
{{ 1000000|intword }}  <!-- 1.0 million -->
{{ 1200000|intword }}  <!-- 1.2 million -->

Output Examples:

1,000,000

one

1st

1.0 million

🔹 Dictionary and JSON Filters

Dictionary filters access nested data, convert objects to JSON, and retrieve values from dictionaries using keys in template syntax.

<!-- Dictionary lookup -->
{{ dict.key }}  <!-- Access by key -->
{{ dict|get_item:"key" }}  <!-- Alternative syntax -->

<!-- JSON formatting -->
{{ data|json_script:"data-json" }}
<script id="data-json" type="application/json">
{"name": "John", "age": 30}
</script>

<!-- Dictionary items -->
{% for key, value in dict.items %}
    <p>{{ key }}: {{ value }}</p>
{% endfor %}
# views.py
def my_view(request):
    context = {
        'user_data': {
            'name': 'Alice',
            'email': '[email protected]',
            'role': 'admin'
        }
    }
    return render(request, 'template.html', context)
<!-- template.html -->
<p>Name: {{ user_data.name }}</p>
<p>Email: {{ user_data.email }}</p>
<p>Role: {{ user_data.role|upper }}</p>

🔹 Chaining Filters

Multiple filters can be chained together using pipes to apply sequential transformations. Filters are applied from left to right in order.

<!-- Chain multiple filters -->
{{ text|lower|truncatewords:5 }}

{{ name|default:"Guest"|title }}

{{ price|floatformat:2|add:10 }}

{{ date|date:"Y-m-d"|default:"No date" }}

<!-- Complex chaining -->
{{ article.content|striptags|truncatewords:20|lower }}

{{ user.email|default:"[email protected]"|lower }}

{{ items|length|add:5|divisibleby:2|yesno:"Even,Odd" }}

Example:

Input: "HELLO WORLD THIS IS A LONG SENTENCE"

Filter: {{ text|lower|truncatewords:3 }}

Output: "hello world this..."

🔹 Filter Summary

Essential Filters by Category:

  • String: upper, lower, title, truncatewords, truncatechars
  • Number: add, floatformat, divisibleby, filesizeformat
  • Date: date, time, timesince, timeuntil, naturaltime
  • List: length, first, last, join, slice, random
  • URL: urlencode, urlize, escape, safe
  • Default: default, default_if_none, yesno, pluralize
  • Humanize: intcomma, intword, ordinal, apnumber

🧠 Test Your Knowledge

Which filter formats a number with commas?