Custom Template Filters
A snippet showing how to define custom template filters in Django.
# models.py
from django.db import models
class Price(models.Model):
amount = models.DecimalField(max_digits=8, decimal_places=2)
def __str__(self):
return f"{self.amount}"
# admin.py
from django.contrib import admin
from .models import Price
@admin.register(Price)
class PriceAdmin(admin.ModelAdmin):
list_display = ("amount",)
# templatetags/shop_extras.py
from django import template
register = template.Library()
@register.filter
def currency(value, symbol="$"):
return f"{symbol}{value:,.2f}"
# templates/price.html
<{% load shop_extras %}>
<p>Total: {{ price.amount|currency:"$" }}</p>
Explanation:
-
Create a
templatetags/package inside the app; add a module and aLibrary(). -
Register functions with
@register.filter; accept optional args for flexibility. -
Load filters in templates with
{% load shop_extras %}.
- Category Templates
- Total Views 495
- Last Modified 28 January, 2026
- Tags #templates #custom filters #python #tags
Previous snippet
Template Filters Example
Next snippet