Add Leading Zeroes to Template Forloop Counter in Django

Add Leading Zeroes to Template Forloop Counter in Django
Show numbers with leading zeroes, such as 01, 02, etc

We can use the classic, {{ forloop.counter }} trick to output the number of the loop iteration (each time we go through the loop, it outputs that number), but it what if your designers want leading zeroes added to those numbers?

Just to be clear these are numbers with leading zeroes:
01
02
03 etc.

We can actually accomplish this with a simple template filter that's already in Django:

<div class="counter">{{ forloop.counter|stringformat:"02d" }}</div>

The stringformat filter takes that number from the forloop.counter and formats it with two "places" and fills those empty places with zeroes. Think of "places" as the slots where numbers could be if they were large enough. For example, 1 gets formatted as 01, because it only takes up one place. Ten (10), however takes two places and since we specified only two places for our leading zero format, the output will be 10.

If you need leading zeroes even into the tens place, you can modify the stringformat like this to print a leading zero even when counting into the tens:

<div class="counter">{{ forloop.counter|stringformat:"03d" }}</div>

This will output numbers in the ones as 001, 002, etc. and numbers in the tens as: 010, 011, etc.

Notes

If you just need one leading zero, it won't break anything if your counter goes beyond the tens places. Here I used the "02d" string format and forced my counter to go into the hundreds, and it output the numbers just fine:

Shows 09 and 10 printed

... After much scrolling:

Shows 99 and 100 printed

String Format Official Breakdown

Flag Meaning
'0' The conversion will be zero padded for numeric values.
Conversion Meaning
'd' Signed integer decimal.

Source: https://docs.python.org/3/library/stdtypes.html#old-string-formatting