Django Template Filters
A filter transforms a value before it's displayed. You attach it to a variable with the pipe character: {{ name|upper }}. Some filters take one argument after a colon, {{ text|truncatewords:10 }}, and filters can be chained left to right: {{ name|lower|capfirst }}.
Text filters
import django
from django.conf import settings
settings.configure(TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates"}])
django.setup()
from django.template import Template, Context
t = Template("""upper: {{ title|upper }}
lower: {{ title|lower }}
title: {{ "the old man and the sea"|title }}
capfirst: {{ "django rocks"|capfirst }}
length: {{ title|length }}
truncatechars: {{ title|truncatechars:12 }}
truncatewords: {{ blurb|truncatewords:4 }}
slugify: {{ title|slugify }}
cut: {{ "1 234 567"|cut:" " }}
center: [{{ "hi"|center:8 }}]
chained: {{ " MIXED case "|lower|cut:" " }}""")
print(t.render(Context({
"title": "Crime and Punishment",
"blurb": "A poor student in St Petersburg commits a terrible crime.",
})))upper: CRIME AND PUNISHMENT
lower: crime and punishment
title: The Old Man And The Sea
capfirst: Django rocks
length: 20
truncatechars: Crime and P…
truncatewords: A poor student in …
slugify: crime-and-punishment
cut: 1234567
center: [ hi ]
chained: mixedcase
Numbers and lists
import django
from django.conf import settings
settings.configure(TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates"}])
django.setup()
from django.template import Template, Context
t = Template("""add: {{ count|add:5 }}
floatformat: {{ price|floatformat:2 }} / {{ 3.0|floatformat }} / {{ 3.14159|floatformat:-2 }}
filesize: {{ bytes|filesizeformat }}
divisibleby: {{ count|divisibleby:3 }}
pluralize: {{ count }} file{{ count|pluralize }}, 1 berr{{ 1|pluralize:"y,ies" }}, 2 berr{{ 2|pluralize:"y,ies" }}
join: {{ tags|join:", " }}
first/last: {{ tags|first }} / {{ tags|last }}
slice: {{ tags|slice:":2" }}
dictsort: {% for p in people|dictsort:"age" %}{{ p.name }}({{ p.age }}) {% endfor %}
yesno: {{ active|yesno:"on,off" }} {{ missing|yesno:"yes,no,maybe" }}""")
print(t.render(Context({
"count": 12, "price": 7.5, "bytes": 2_500_000, "active": True, "missing": None,
"tags": ["python", "django", "web"],
"people": [{"name": "Bao", "age": 41}, {"name": "Cuc", "age": 19}],
})))add: 17
floatformat: 7.50 / 3 / 3.14
filesize: 2.4 MB
divisibleby: True
pluralize: 12 files, 1 berry, 2 berries
join: python, django, web
first/last: python / web
slice: ['python', 'django']
dictsort: Cuc(19) Bao(41)
yesno: on maybe
filesizeformat (and timesince below) join the number and unit with a non-breaking space, so the value never wraps across two lines. Notice also that slice printed a Python list — and its quotes were HTML-escaped. Lists are usually better shown with join or a loop.
Dates
The date filter formats date/datetime objects with PHP-style format characters. timesince and timeuntil describe the distance between two dates:
import django, datetime
from django.conf import settings
settings.configure(USE_TZ=False, TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates"}])
django.setup()
from django.template import Template, Context
t = Template("""{{ d|date:"Y-m-d" }}
{{ d|date:"D, d M Y" }}
{{ d|date:"l j F Y, H:i" }}
{{ d|date:"SHORT_DATE_FORMAT" }}
{{ start|timesince:d }} between them""")
print(t.render(Context({
"d": datetime.datetime(2026, 3, 8, 14, 5),
"start": datetime.datetime(2026, 1, 1, 9, 0),
})))2026-03-08
Sun, 08 Mar 2026
Sunday 8 March 2026, 14:05
03/08/2026
2 months, 1 week between them
| Format character | Meaning | Example |
|---|---|---|
Y / y |
4- / 2-digit year | 2026 / 26 |
m / n |
month with / without leading zero | 03 / 3 |
d / j |
day with / without leading zero | 08 / 8 |
M / F |
month abbreviation / full name | Mar / March |
D / l |
weekday abbreviation / full name | Sun / Sunday |
H:i |
24-hour time | 14:05 |
Defaults and escaping
| Filter | Effect |
|---|---|
default:"x" |
use "x" if the value is falsy |
default_if_none:"x" |
use "x" only if the value is None |
safe |
mark trusted HTML as safe (no escaping) |
escape / force_escape |
escape HTML explicitly |
striptags |
remove HTML tags |
linebreaksbr |
turn newlines into <br> |
urlize |
turn URLs in text into links |
json_script:"id" |
safely embed data as JSON for JavaScript |
import django
from django.conf import settings
settings.configure(TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates"}])
django.setup()
from django.template import Template, Context
t = Template("""[{{ zero|default:"n/a" }}] [{{ zero|default_if_none:"n/a" }}] [{{ none|default_if_none:"n/a" }}]
{{ bio|striptags }}
{{ note|linebreaksbr }}
{{ data|json_script:"page-data" }}""")
print(t.render(Context({
"zero": 0, "none": None,
"bio": "<b>Loves</b> <i>tea</i>",
"note": "line one\nline <two>",
"data": {"user": "Ly", "tags": ["a", "b"]},
})))[n/a] [0] [n/a]
Loves tea
line one<br>line <two>
<script id="page-data" type="application/json">{"user": "Ly", "tags": ["a", "b"]}</script>
Writing a custom filter
A filter is just a Python function registered in a template library. In a project the library lives in <app>/templatetags/<name>.py and templates load it with {% load name %}. In the playground we register the library through the builtins option so no load is needed:
import sys, types, django
from django.conf import settings
sys.modules["shop_filters"] = lib = types.ModuleType("shop_filters")
settings.configure(TEMPLATES=[{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"OPTIONS": {"builtins": ["shop_filters"]},
}])
from django import template
lib.register = register = template.Library()
@register.filter
def vnd(amount):
"""Format a number as Vietnamese dong: 125000 -> 125.000 ₫"""
return f"{int(amount):,}".replace(",", ".") + " ₫"
@register.filter
def times(value, factor):
return value * factor
django.setup()
from django.template import Template, Context
t = Template("Price: {{ price|vnd }} | x3: {{ price|times:3|vnd }}")
print(t.render(Context({"price": 125000})))Price: 125.000 ₫ | x3: 375.000 ₫
# books/templatetags/shop_filters.py (project version; add an empty __init__.py too)
from django import template
register = template.Library()
@register.filter
def vnd(amount):
return f"{int(amount):,}".replace(",", ".") + " ₫"{% load shop_filters %}
{{ book.price|vnd }}Test yourself
What does {{ "hello world"|title }} output?
- HELLO WORLD
- Hello world
- Hello World
- hello world
Which filter shows a fallback only when the value is None (but keeps 0 and "")?
- default
- default_if_none
- yesno
- safe
How do you pass an argument to a filter?
- {{ value|filter(arg) }}
- {{ value|filter:arg }}
- {{ value|filter arg }}
- {{ filter value arg }}