I would like something similar to the string formatting from the standard library.
'%' Percentage. Multiplies the number by 100 and displays in fixed ('f') format, followed by a percent sign.
filter(option=o). count() perc = cnt * 100 / total_count perc_dict. update( {o. value: perc} ) #after this the perc_dict will have percentages for all options that you can pass to template.
'%' Percentage. Multiplies the number by 100 and displays in fixed ('f') format, followed by a percent sign.
Django Template Engine provides filters which are used to transform the values of variables;es and tag arguments. We have already discussed major Django Template Tags. Tags can't modify value of a variable whereas filters can be used for incrementing value of a variable or modifying it to one's own need.
I was looking for almost the same question and found the widthratio template tag. Instead of having the percentage already calculated like in your question, you can use this tag to calculate the percentage in the template from the original value and total value against which your percentage is calculated. It does the job if you only need an integer percentage without precision:
{% widthratio value total_value 100 %}
Ref: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#widthratio
In case somebody is looking for the answser, this is how I solved the problem with a custom templatetag:
from django import template register = template.Library() @register.filter def percentage(value): return format(value, "%")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With