Django模板过滤器:将floatformat应用于widthratio

时间:2016-12-15 10:45:02

标签: django django-templates

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

1 个答案:

答案 0 :(得分:2)

据我所知,没有标准的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过滤器的组合。