gpt4 book ai didi

Django 模板过滤器 : apply floatformat to widthratio

转载 作者:行者123 更新时间:2023-12-02 00:49:28 24 4
gpt4 key购买 nike

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

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

目前它返回一个整数。

我如何在此处应用 floatformat,或者我是否需要在 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 过滤器。但是您别无选择。首先是你所说的在 View 中做数学。另一个正在使用 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 的组合过滤器。

关于Django 模板过滤器 : apply floatformat to widthratio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41162197/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com