问题
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