Search code examples
pythondjangodjango-tables2

How to add counter column in django-tables2?


I'm trying to add a counter on the first column of a table using django-tables2, but the solution below is only showing all 0 under the # column. How should I add a column that will have a column that numbers the rows?

tables.py:

import django_tables2 as tables
from profiles.models import Track
import itertools
counter = itertools.count()

class PlaylistTable(tables.Table):

    priority = tables.Column(verbose_name="#", default=next(counter))

    class Meta:
        model = Track
        attrs = {"class": "paleblue"}
        orderable = False
        fields = ('priority', 'artist', 'title')

My template:

{% render_table table %}

Solution

  • Other answers all have the itertools.count instance in the toplevel scope of the tables.py file. This makes the counter persist between page loads, it will only be reset when the server is restarted. A better solution is to add the counter as instance variable on the table like this:

    import django_tables2 as tables
    import itertools
    
    class CountryTable(tables.Table):
        counter = tables.Column(empty_values=(), orderable=False)
    
        def render_counter(self):
            self.row_counter = getattr(self, 'row_counter', itertools.count())
            return next(self.row_counter)
    

    This will make sure the counter is reset every time the table is instantiated.