Mahdi mehrabi
Mahdi mehrabi

Reputation: 1754

check variable is numerical django template

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

Answers (2)

southernegro
southernegro

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

NS0
NS0

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

Related Questions