Django 模板过滤器:将 floatformat 应用于 widthratio [英] Django template filters: apply floatformat to widthratio

查看:28
本文介绍了Django 模板过滤器:将 floatformat 应用于 widthratio的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

widthformat automatically rounds up. However I would like to perform a division and round up to n decimal places in the template tag if possible. For instance:

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

目前它返回一个整数.

我将如何在此处应用 floatformat,或者我是否需要在视图中执行此工作?

How would I apply floatformat here, or do I need to do this work in the view?

使用模型的替代方法

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 过滤器.但是您几乎没有其他选择.首先是正如你所说的在视图中做数学.另一个是使用自定义模板过滤器:

As far as I know there is no standard Django filter for that. But you have few alternatives. First is as you said do math in the view. Another one is using custom template filter:

from django import template
register = template.Library()

@register.filter
def div(value, div):
    return round((value / div) * 100, 2)

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

In template you can use it this way:

{{ a|div:b }}

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

Third option if you are using Django 1.8 and less is django-mathfilters you could try to use combinations of it's div and mult filters and Django floatformat filter.

这篇关于Django 模板过滤器:将 floatformat 应用于 widthratio的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆