Percentage Django template tag

Filed under: Python | 1 Comment

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

def percentage(fraction, population):
        return "%.2f%%" % ((float(fraction) / float(population)) * 100)
    except ValueError:
        return ''


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


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