Reputation: 1754
Hi I want to check if my variable is numeric in Django template and I tried this code
{% if isnumeric(item) %}
<h1>{{item}}</h1>
{% endif %}
but this throws me this error
Could not parse the remainder: '(item)' from 'isnumeric(item)'
I tried to find a builtin template tag or filter in this page https://docs.djangoproject.com/en/3.1/ref/templates/builtins/ of Django document
and I searched for this question in StackOverflow too but I did not found anything related
Upvotes: 0
Views: 2845
Reputation: 394
isnumeric() python fuction doesn't take any parameters
Make a fuction in your model:
def isnumeric(self):
item = self.item
if item.isnumeric() is True:
return True
else:
return False
then in your template:
{% if item.isnumeric %}
<h1>{{item}}</h1>
{% endif %}
With this, you can use the isnumeric() function in your template. You can add an else statement too.
Take a look to isnumeric() function
Upvotes: 2
Reputation: 6126
I don't believe there's a built in template function to check for that. One way to do it is to write your own:
https://docs.djangoproject.com/en/3.1/howto/custom-template-tags/
The code would look something like:
my_filters.py
from django import template
register = template.Library()
@register.filter()
def is_numberic(value):
return value.isdigit()
And in the html:
{% load my_filters %}
{% if item|is_numeric %}
...
Upvotes: 2