django python – how to list the progressive numeric value of a list

I would like to render a list obj with the progressive number as follow:

  1. List item 1 #(with id=10)
  2. List item 2 #(with id=2)
  3. List item 3 #(with id=3)
  4. and so on…

I don’t want to use the id/pk, since I am ordering the objects alphabetically.

I’m using class based views:

class EquipmentType_ListView(ListView):    model               = EquipmentType    template_name       = 'equipment/equipment_type.html'     context_object_name = 'obj_list' #default = object_list    ordering            = ['type']  

with a very simple model:

class EquipmentType(models.Model):    type        = models.CharField(max_length=100, unique=True)    date_posted = models.DateTimeField(auto_now_add=True) 

and the corresponding html:

{% extends 'equipment/base.html'%} {% block content%} {% for instance in obj_list %}  <article class="media content-section">   <div class="media-body">     <div class="article-metadata">       <a class="mr-2" href="#">{{ instance.type }}</a>         <small class="text-muted">{{ instance.date_posted}}</small>     </div>   </div> </article> {% endfor %} 

My question is, should I add the code to the views.py or directly to the html file(for cycle)?

I’m not an experienced programmer, but I feel like it should be straight forward. Also it could be very useful to apply generically on all king of list elements rendered out.

I was thinking there should be some "method" on the "for instance in obj_list" where you could print out directly on the html the instance’s relative number, or perhaps adding an inner for cycle to do the work. I’m struggling to find anything useful on google searches.

thank you very much for the help.

PS: It is my first post on stackoverflow, I hope I’ve done everything correctly 🙂

Carlo

Add Comment
1 Answer(s)

Django provides support for this natively: {{ forloop.counter }}

{% extends 'equipment/base.html'%} {% block content%} {% for instance in obj_list %}  <article class="media content-section">   <div class="media-body">     <div class="article-metadata">       <a class="mr-2" href="#">{{ forloop.counter }}. {{ instance.type }}</a>         <small class="text-muted">{{ instance.date_posted}}</small>     </div>   </div> </article> {% endfor %} 
Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.