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

查看:73
本文介绍了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天全站免登陆