Django custom template filters
In Django project, we need to format data type after grab them from database, such as round float number to two decimals or show N/A when number is 0, these need to do some data preparations using one Django’s feature: Filters.
Prerequisite
Django’s template language comes with a wide variety of built-in tags and filters designed to address the presentation logic needs of your application. Nevertheless, you may find yourself needing functionality that is not covered by the core set of template primitives. You can extend the template engine by defining custom tags and filters using Python, and then make them
available to your templates using the tag
1 {% load tags %}
You need to know that filters have to put into one certain Django application, which means Django project must have at least one application then and use custom filters.
Following the steps below:
Create a folder named ‘templatetags’ and create a
__init__.py
file in order to convert it into a python package, then the file structure in your app might like this:1234567polls/__init__.pymodels.pytemplatetags/__init__.pymytags.pyviews.pyMake sure your app name is included in term INSTALLD_APPS in file settings.py:
12345678910INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','query','bootstrap3',]
as it shows above, my app name is query.
Writing custom template filters
Filter is actually like a function or a method, django would transfer raw data to filter before transfer them to the place they should to, then filter would transfer data that are filtered to those places.
After finished these, you can import filters as
in your html pages to call filters saved in mytags.py in templatetags folder, so what we need to do is coding in the mytags.py
or so files.
Definition of custom filters
12345def thcut(value):s = '%.2f' % float(value)if s == '0.00':return 'N/A'return re.sub(r"(/d)(?=(/d/d/d)+(?!/d))", r"/1,", s)Register filter
register filter in template.Library() instance, if not, project will not scan this filter12from django import templateregister = template.Library()add registration before:
123456def thcut(value):s = '%.2f' % float(value)if s == '0.00':return 'N/A'return re.sub(r"(/d)(?=(/d/d/d)+(?!/d))", r"/1,", s)This method use decorator to register, another way is to use Library.filter(name,function,is_safe=False,needs_autoescape=False,excepts_localtime=False) function, it has two argument:
- name : name of decorator, string type, if none, django set function name as default.
- function : name of fucntion, string type.