Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a django template filter to display percentages?

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.

like image 555
jbochi Avatar asked May 01 '10 19:05

jbochi


People also ask

How does Django calculate percentage?

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.

What does percentage include percentage does in Django?

'%' Percentage. Multiplies the number by 100 and displays in fixed ('f') format, followed by a percent sign.

What does filter do in Django template?

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.


2 Answers

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

like image 196
JeromeParadis Avatar answered Sep 20 '22 10:09

JeromeParadis


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, "%") 
like image 33
jbochi Avatar answered Sep 19 '22 10:09

jbochi