Django template filters: apply floatformat to widthratio

╄→гoц情女王★ 提交于 2021-02-05 06:40:29

问题


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>

Currently it returns an integer.

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

The alternative way using the model

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:


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 }}

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.



来源:https://stackoverflow.com/questions/41162197/django-template-filters-apply-floatformat-to-widthratio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!