Percentage Django template tag

Filed under: Python | 1 Comment

Here’s a handy template filter that calculates percentages inside Django templates.

@register.filter(name='percentage')
def percentage(fraction, population):
    try:
        return "%.2f%%" % ((float(fraction) / float(population)) * 100)
    except ValueError:
        return ''

Usage

There were {{ yes.count }} yes votes ({{ yes.count|percentage:votes.count }}) out of {{ votes.count }} responses.

Result

There were 40 yes votes (40%) out of 100 responses.

Read the latest posts

One Response to “Percentage Django template tag”

  1. stalker says:

    Nice tag, I just added check when float(population) is 0

Leave a Reply to stalker