django-tables2 不显示列 headers

django-tables2 not displaying column headers

我正在根据此模型(在 users/models.py 中)使用 django-tables2 生成排行榜:

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

tables.py中,我selectusernamepoints,按后者排序:

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

views.py,我有

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

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

最后,使用 {% load render_table from django_tables2 %}{% render_table table %}leaderboard.html 模板中呈现。

table 渲染良好,但没有任何列 headers。

尝试 1: 我根据 this suggestion, under the assumption that this should show by default (as per this) 向 CustomUser 模型的 points 字段添加了一个 verbose_name,但无济于事。

尝试 2: 下面给出了列名,但只有当我设置 orderable=False 时,这意味着我不能再按 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'

我做错了什么?

万一其他人遇到这个问题,这里有一个解决方案:

首先,在 table class 中的每一列上设置 orderable=False,以确保所有 headers 都显示:

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'

然后,在CustomUser模型上添加一个Meta,如下,让table按点排序:

class Meta:
        ordering = ['-points']