Percentage Django template tag
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.
Nice tag, I just added check when float(population) is 0