Loop Counter in Django View

Make Loop counter in DJango template language, in html templates.


Most time loops are used to print out information in array, which won't be easy to read if printed without numeric counter. The information may have a unique ID which might not be sequential or represent the exact count of items printed.

It's straight forward task, use a variable initialized to 1 then increment it with each run var++. But django doesn't allow variable deceleration in templates other than using custom tags, which is not recommended. But Django brings in the box an automatically creates a variable called forloop.counter that holds the current iteration index.

{% for variable in variables %} 
  {{ forloop.counter }} : {{ variable.variable_name }} 
{% endfor %}

The forloop.counter starts with 1, this means the first entry will start with 1 and increments till the loop iterates.

If you really wanted to do this it is possible with custom tags but for the most part the philosophy you want to follow is that mostly anything you want to do that would require this should be done in the view and the template should be reserved for very simple logic.


Wow ! you have someting to tell us. That's great! Please keep in mind that comments are moderated, we employ rel="nofollow" for links, avoid using a spammy word or a domain in name field, it might end up as a Spam. Thanks for reading.

Last 5 Articles

All Articles >

  1. Mitigating Risks In Custom Software Development

  2. Container Security to Secure Microservices

  3. Strategic Messaging

  4. URL Shortener in Django

  5. MySQL as Database Option


News Letter

Subscribe to our email newsletter for useful tips and valuable resources, sent out every new article release.