Django Template Filters
A template filter changes a value as it shows. The | mark joins the filter to the value.
Make the view
The view passes a name, a heading, and a list. The template file changes each one.
def page(request):
return render(request, "page.html", {"name": "Mara", "heading": "first post", "items": ["One", "Two", "Three"]})Change the values in the file
Each line uses one filter. The last line shows Guest when no guest passes.
<p>{{ name|upper }}</p>
<p>{{ name|lower }}</p>
<p>{{ heading|title }}</p>
<p>{{ items|length }} posts</p>
<p>{{ guest|default:"Guest" }}</p>Ask for the page
The test client asks for the page and prints the changed values.
from django.test import Client
client = Client()
print(client.get("/page/").content.decode())Example
import django
from django.conf import settings
settings.configure(
DEBUG=True,
SECRET_KEY="key",
ROOT_URLCONF=__name__,
ALLOWED_HOSTS=["*"],
TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True}],
)
django.setup()
from django.template import Context, Template
template = Template("<p>{{ name|upper }}</p>\n<p>{{ name|lower }}</p>\n<p>{{ heading|title }}</p>\n<p>{{ items|length }} posts</p>\n<p>{{ guest|default:\"Guest\" }}</p>")
print(template.render(Context({"name": "Mara", "heading": "first post", "items": ["One", "Two", "Three"]})))
Key points
- {{ name|upper }} shows the value in capital letters.
- Use |lower to show a value in small letters.
- Use |title to capitalize the first letter of each word.
- Use |length to count the items in a list.
- Use |default:"Guest" to show Guest when the value is missing.
- A filter changes the shown value, not the value itself.
In this example, the setup lines configure Django. The program renders a template string with Template and Context. A real project keeps templates in files. Each line uses one filter on the same values. The prints show the changed values in order.
Note
Filters chain with more | marks, like {{ name|lower|title }}.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does {{ name|upper }} show when name is Mara?