Django test if the variable is numeric -
looks question should covered, after spending time, did not find how check variable numeric in django template.
{% if my_var.isnumeric %} # {% endif %}
update learnt below discussion, there seems no built-in tag check this, , end having create our own template tag.
assuming "numeric" means "contains digits" (and no decimal point, no minus sign, etc.)
custom filter best bet:
from django import template register = template.library() @register.filter(is_safe=true) def is_numberic(value): return "{}".format(value).isdigit()
docs custom template filters: https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/
usage in templates:
{% load your_custom_lib %} ... {% if something|is_numberic %}...
if consider integers numeric (positive , negative), function becomes:
try: int("{}".format(value)) except valueerror: return false else: return true
in case "numeric" means "integer or float", use float
instead of int
. note recognize -12e3
numeric, because:
>>> -12e3 -12000.0
Comments
Post a Comment