DEV Community

Cover image for Custom Template Filter In Django
Desmond
Desmond

Posted on • Updated on

Custom Template Filter In Django

I ran into an issue today where I needed to use an integer from my model to generate a list of numbers with the python range function in my template ,but django doesn't support that and it wasn't right for my use case as I had to generate the list dynamically. I decided to create a custom template filter.

To create a custom template filter, first create a directory in your apps folder (where you have views.py) called templatetags and add an init.py file.

Your file directory should look like this

I created a file called my_extras.py which would contain our custom tag.

We've now named our custom tag times which we can now use in our templates.

In any template we can now load our tags in our html file like this {% load my_extras %}

Now to the reason why I needed to do it this way rather than including it in my context.

Here's my view
"""python
def listview(request):
list = List.objects.all()
return render(request, 'foo.html',
{'list':list}"""

In foo.html I have a form which needs to have a max order quantity determined by the user. So if {{list.quantity}} in my query set above returns 10 I have to print 1-10 in my select html form element.

Thanks for your time, any better implementation of this is welcome.

Top comments (0)