Search code examples
djangodjango-tables2

django-tables2 not displaying column headers


I'm generating a leaderboard using django-tables2 based on this model (in users/models.py):

class CustomUser(AbstractUser):
    points = models.DecimalField(
        max_digits=20, 
        decimal_places=2,
        default=Decimal('1000.00'))

In tables.py, I select username and points, and order by the latter:

class UserTable(tables.Table):
    class Meta:
        model = CustomUser
        fields = ('username','points')
        order_by = '-points'
        template_name = 'django_tables2/bootstrap.html' 

In views.py, I have

def leaderboard_list(request):
    table = UserTable(CustomUser.objects.all())
    RequestConfig(request).configure(table)

    return render(request, 'leaderboard.html', {
        'table': table
    })

Finally, this gets rendered in the leaderboard.html template with {% load render_table from django_tables2 %} and {% render_table table %}.

The table renders fine, but without any column headers.

Attempt 1: I added a verbose_name to the points field of the CustomUser model in light of this suggestion, under the assumption that this should show by default (as per this), but to no avail.

Attempt 2: The following gives me the column names, but only when I set orderable=False, which means I can no longer order by points:

class UserTable(tables.Table):
    username = tables.Column(verbose_name='User name', orderable=False, accessor=Accessor('username'))
    points = tables.Column(verbose_name='Points', orderable=False, accessor=Accessor('points'))
    class Meta:
        model = CustomUser
        fields = ('username','points')
        order_by = '-points'
        template_name = 'django_tables2/bootstrap.html'

What am I doing wrong here?


Solution

  • In case anyone else comes to have this issue, here's one solution:

    First, set orderable=False on each column in the table class, to ensure that all the headers are showing:

    class UserTable(tables.Table):
        username = tables.Column(verbose_name='Username', orderable=False, accessor=Accessor('username'))
        points = tables.Column(verbose_name='Points', orderable=False, accessor=Accessor('points'))
    
        class Meta:
            model = CustomUser
            fields = ('username','points')
            template_name = 'django_tables2/bootstrap.html'
    

    Then, add a Meta as follows on the CustomUser model, as follows, to have the table order by points:

    class Meta:
            ordering = ['-points']