DEV Community

Cover image for Custom Template Filter In Django

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 called templatetags and add an file.

Your file directory should look like this

I created a file called 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
def listview(request):
list = List.objects.all()
return render(request, 'foo.html',

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)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!