How to Create a Custom Filter in Django

In this article, we show how to create a custom filter in Django.
What is a custom filter?
Before we define what a custom filter is, we must know that django comes with many pre-built filters, such as title (which makes all the words capitalized), lowercase (which makes all the words lowercase), etc.
A full list of django's pre-built filters can be found at the following page: https://docs.djangoproject.com/en/5.1/ref/templates/builtins/
However, if none of these filters serve to fulfill what you need, the only other option is to create your own.
This may be a filter to highlight matching search terms in a text or shorten a text to a certain amount of words.
Let's see what we must do to make this work.
What we need to do first to create a directory within our django project that will hold the code for this custom filter. We name this directory, templatetags.
You can create this anywhere that you like.
Within this directory, we must create a __init__ py file.
We must also create a file, which you can mame anything, within this directory. I call mind, custom_filters.py
Within this python file, we specify the code for our filter.
In this example, a filter is created which highlights in yellow a search term that a user enters.
Next within our template that will contain this custom filter tag, we must specify, {% load custom_filters %}, near the top of the page.
We would change this to whatever you called the python file that contains the code for the custom filter.
Next, you are free to use this custom filter anywhere in your code.
So if you want to add this custom filter to {{searchresult}}, the code would be, {{searchresult highlight_search:query}}, where query represents the search term that the user entered in. This search to highlight the user's search term within the larger text.
And this is how custom filters work in django.
The full documentation is to create a custom filter in Django is shown at this page: https://docs.djangoproject.com/en/5.1/howto/custom-template-tags/
You should only have one directory within your django project that contains the directory, templatetags.
This can be in any app in your Django project.
You can now use this custom filter within any template page site wide.
Related Resources
How to Randomly Select From or Shuffle a List in Python