Whether you're writing a custom label or a filter, the first thing to do is create a template library (the basic structure that Django can import).
Creating a template Library is a two-step walk:
First, decide which Django application the template Library should be placed in. If you create an app from manage.py Startapp, you can put it there, or you can create an app for the template gallery alone. We recommend using the latter because your filter may be useful in later projects.
No matter how you do it, be sure to add your app to Installed_apps. We will explain this later.
Second, create a templatetags directory in the appropriate Django application package. This directory should be at the same level as models.py, views.py, and so on. For example:
books/ __init__.py models.py templatetags/ views.py
Create two empty files in Templatetags: A __init__.py (tell Python that this is a package containing Python code) and a file to store your custom label/filter definitions. The name of the second file will later be used to load the tag. For example, if your custom label/filter is in a file called poll_extras.py, you need to write the following in the template:
{% load Poll_extras%}
The {% load%} tag checks the settings in Installed_apps, allowing only the template libraries in the installed Django application to be loaded. This is a security feature that allows you to deploy many of the template Library's code on a single computer without exposing them to every Django installation.
If you write a template library that is not associated with any particular model/view, it is perfectly normal to get a Django application package that contains only the Templatetags package. There is no limit to how many modules are placed in the Templatetags package. What you need to know is that the {%load%} statement loads the tag/filter by specifying the Python module name instead of the application name.
Once you have created a Python module, you can write some Python code based on whether you want to write a filter or a label.
As a legitimate tag library, the module needs to include a module-level variable named register. This variable is a template. An example of the library is the data structure of all registered tags and filters. So, please insert the following statement at the top of your module:
From django Import templateregister = template. Library ()
Attention
Read the Django default filter and tag source, where there are a number of examples. They were: django/template/defaultfilters.py and django/template/defaulttags.py. Some of the applications in Django.contrib also contain template libraries.
Once you have created the register variable, you can use it to create filters and labels for the template.