【问题标题】:Django template filters: apply floatformat to widthratioDjango模板过滤器:将floatformat应用于widthratio
【发布时间】:2017-04-30 22:33:33
【问题描述】:

widthformat 自动向上取整。 但是,如果可能,我想在模板标签中执行除法并四舍五入到 n 位小数。 例如:

    <h4>Strike Rate: {% widthratio selected_replies user.projectreply_set.count 100 %}</h4>

目前它返回一个整数。

我将如何在此处应用 floatformat,还是需要在视图中完成这项工作?

使用模型的另一种方式

class UserProfile(models.Model):
    ....
    ....
    def get_strike_rate(self):
        selected_replies = self.user.projectreply_set.filter(is_selected_answer=True).count()
        my_replies = self.user.projectreply_set.count()
        if my_replies >0:
             return round((selected_replies/my_replies)*100.0,2)
        else:
             return 0

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    据我所知,没有标准的 Django 过滤器。 但是您几乎没有其他选择。首先是如你所说在视图中做数学。 另一个是使用custom template filter

    from django import template
    register = template.Library()
    
    @register.filter
    def div(value, div):
        return round((value / div) * 100, 2)
    

    在模板中你可以这样使用:

    {{ a|div:b }}
    

    如果您使用的是 Django 1.8 及以下版本,则第三个选项是 django-mathfilters,您可以尝试使用它的 div 和 mult 过滤器以及 Django floatformat 过滤器的组合。

    【讨论】:

      猜你喜欢
      • 2012-02-23
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      • 2011-04-12
      • 2012-08-18
      • 1970-01-01
      • 2016-05-07
      • 1970-01-01
      相关资源
      最近更新 更多