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) |
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> | |
Thanks for your time, any better implementation of this is welcome.
Top comments (0)