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)

The JavaScript Brief

1. Top 5 MERN STACK projects to improve your practical understanding

Boost your MERN Stack development skills by undertaking interesting beginner projects. These five engaging projects cover web applications and range from social media website applications to geo-social networking maps. Hone your understanding and apply modern techniques backed up by hands-on experience.

2. How To Optimize Your React App’s Performance

Learn the best optimizing techniques to make your React applications faster and more efficient. Focusing on the identification of performance bottlenecks and common pitfalls to avoid, these optimization strategies will keep your applications running smoothly even when faced with growing complexity.

3. A story of let, const, object mutation, and a bug in my code

In the pursuit of bug-free code, explore an incident involving a mix-up between const and let, making sure your custom code works effectively with third

party documentation. Discover best practices on program flow and learn about JavaScript's unpredictable aspects to ensure your core code is robust.