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 %}
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.
From the documentation of Column
default (str or callable)
:The default value for the column. This can be a value or a callable object
[1]
. If an object in the data providesNone
for a column, the default will be used instead.
[1] - The provided callable object must not expect to receive any arguments.
What you are passing next(counter)
you are passing the result of a function which seems to be an integer.
You can either define a function:
def next_count():
return next(counter)
and, use it as default:
priority = tables.Column(verbose_name="#", default=next_count)
Or, you can use the lambda function as mentioned in @Sayse's comments:
priority = tables.Column(verbose_name="#", default=lambda: next(counter))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With