[Django]-Is there a Django template tag that will convert a percentage to a human readable format?

4πŸ‘

I went ahead and created a template tag filter like this:

@register.filter
def to_percent(obj, sigdigits):
    if obj:
        return "{0:.{sigdigits}%}".format(obj, sigdigits=sigdigits)
    else: return obj

I was surprised to see the link shared in another answer didn’t have a clean solution like that yet. The best one I saw used a try block instead of the if obj… I personally want to see an error in my use case, but that’s up to you.

Still, good to know there isn’t a more "Django" way to do it that I saw. You’d use this in your template like…

{{{{mymodel.some_percentage_field|to_percent:2}}

where 2 is the number of significant digits you want.

πŸ‘€Nick Brady

1πŸ‘

As Michael mentioned above, I will suggest you to write your own template tag for that : https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/

πŸ‘€Vipin Joshi

1πŸ‘

You can do this with Django built-in template tag withraatio

{% widthratio this_value max_value max_width as width %}

If this_value is 175, max_value is 200, and max_width is 100, the image in the above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5 which is rounded up to 88).

You can also see the details here

πŸ‘€shafikshaon

0πŸ‘

If you only have to format a number with percent, for example β€œ65%” :

{{ number|stringformat:"d%%" }}
πŸ‘€Cyril

-1πŸ‘

Maybe use one of these solutions: Is there a django template filter to display percentages?

Hope it helps. If not, write your own simple filter πŸ™‚

Leave a comment