【问题标题】:How can I output a multiply expression in a Django template?如何在 Django 模板中输出乘法表达式?
【发布时间】:2019-04-05 21:05:09
【问题描述】:

我正在使用 Django 和 Python 3.7。在我看来,如何输出表达式?我想做

<td>{{ fp_stat.avg_score * dow_index }}</td>

但我收到此错误

Could not parse the remainder: ' * dow_index' from 'fp_stat.avg_score * dow_index'

我不希望在我的模型中创建额外的属性,但如果这是唯一的方法,那么我想我必须这样做。

【问题讨论】:

    标签: django python-3.x templates view


    【解决方案1】:

    您可以使用模板过滤器来做这种事情。

    例如;

    @register.filter
    def multiply(value, arg):
        try:
            return value * arg
        except Exception:
            return ''
    

    所以你可以这样做{{ fp_stat.avg_score|multiply:dow_index }}

    还有一个包可以更好地实现这种类型的过滤器;

    https://pypi.org/project/django-mathfilters/

    【讨论】:

      猜你喜欢
      • 2013-11-04
      • 2015-09-02
      • 1970-01-01
      • 2018-12-03
      • 2016-10-19
      • 2020-05-12
      • 2014-01-02
      • 1970-01-01
      • 2012-07-26
      相关资源
      最近更新 更多