DEV Community

Cover image for Custom Template Filter In Django
Desmond
Desmond

Posted on • Edited on

2 1

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

<your_app_name>/
__init__.py
models.py
templatetags/
__init__.py
my_extras.py
views.py

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

from django import template
register = template.Library()
@register.filter(name='times')
def times(number):
"""
Returns a numerical loop with the built in python range function
"""
return range(number)
view raw my_extras.py hosted with ❤ by GitHub

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.

{% for item in list %}
<form>
{{ item.name }}
<select>
{% for i in ticket.quantity|add:"1"|times%}
   <option value="1">{{ i }}</option>
 {% endfor %}}
{% endfor %}
</select>
</form>
view raw Foo.html hosted with ❤ by GitHub

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series