Template filters help change how data looks when shown on a webpage. They make data easier to read or handle without changing the original data.
0
0
Template filters (date, length, default) in Django
Introduction
When you want to show a date in a friendly format like 'Jan 1, 2024' instead of a long timestamp.
When you need to count how many items are in a list or characters in a string before showing it.
When you want to show a default message or value if some data is missing or empty.
Syntax
Django
{{ value|filter_name }}
{{ value|filter_name:'argument' }}Filters are added after a pipe symbol (|) inside double curly braces.
Some filters like
date take an argument to specify the format.Examples
Shows the date in a format like 'January 1, 2024'.
Django
{{ my_date|date:'F j, Y' }}Shows how many items are in the list.
Django
{{ my_list|length }}Shows 'Guest' if user_name is empty or missing.
Django
{{ user_name|default:'Guest' }}Sample Program
This template shows how to use the date, length, and default filters. It formats a date, counts list items, and provides a fallback name.
Django
{% load tz %}
<p>Original date: {{ my_date }}</p>
<p>Formatted date: {{ my_date|date:'M d, Y' }}</p>
<p>List length: {{ my_list|length }}</p>
<p>User name: {{ user_name|default:'Anonymous' }}</p>OutputSuccess
Important Notes
The date filter uses Django's date format strings, which are different from Python's datetime formats.
The length filter works on strings, lists, and other countable objects.
The default filter shows the default if the value is falsy (e.g., None, empty string/list, 0, False).
Summary
Template filters change how data looks in templates without changing the data itself.
date formats dates, length counts items, and default provides fallback values.
Filters are easy to add using the pipe symbol inside double curly braces.