【问题标题】:check variable is numerical django template检查变量是数字 django 模板
【发布时间】:2020-12-19 02:31:00
【问题描述】:

您好,我想在 Django 模板中检查我的变量是否为数字 我试过这段代码

{% if isnumeric(item) %}
<h1>{{item}}</h1>
{% endif %}

但这会引发这个错误

无法解析余数:'(item)' from 'isnumeric(item)'

我试图在这个页面中找到一个内置的模板标签或过滤器 Django 文档的https://docs.djangoproject.com/en/3.1/ref/templates/builtins/

我也在 StackOverflow 中搜索过这个问题 但我没有找到任何相关的东西

【问题讨论】:

  • item 到底是什么?一个字符串?
  • @WillemVanOnsem 它可能是字符串或浮动或列表或其他任何东西,我想检查它是否是一个数字

标签: django django-templates


【解决方案1】:

我不相信有一个内置的模板函数来检查它。一种方法是自己编写:

https://docs.djangoproject.com/en/3.1/howto/custom-template-tags/

代码如下所示:

my_filters.py

from django import template
register = template.Library()
@register.filter()
def is_numberic(value):
    return value.isdigit()

在 html 中:

{% load my_filters %}

{% if item|is_numeric %}
    ...

【讨论】:

    【解决方案2】:

    isnumeric() python 函数不带任何参数

    在你的模型中创建一个函数:

    def isnumeric(self):
        item = self.item
        if item.isnumeric() is True:
            return True
        else:
            return False
    

    然后在您的模板中:

    {% if item.isnumeric %}
    <h1>{{item}}</h1>
    {% endif %}
    

    这样,您可以在模板中使用 isumeric() 函数。您也可以添加 else 语句。

    看看isnumeric() function

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-07
      • 2012-10-07
      • 2021-01-18
      • 2019-04-08
      • 2011-09-07
      • 2013-07-14
      • 2013-11-28
      相关资源
      最近更新 更多