You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为django_tables2指定Bootstrap表格样式类?

给django-tables2的表格添加Bootstrap 4自定义样式

要给你的PersonTable应用Bootstrap 4文档里的各类表格样式,有几种简单直接的实现方式:

1. 全局给表格绑定Bootstrap类

直接在Table类的Meta中添加attrs属性,把Bootstrap的表格类直接绑定到<table>标签上,这是最快捷的方式:

class PersonTable(tables.Table):
    class Meta:
        model = player_hardware
        template_name = "django_tables2/bootstrap-responsive.html"
        # 可组合Bootstrap各类表格样式,比如条纹、悬停、边框等
        attrs = {
            "class": "table table-striped table-hover table-bordered"
        }

Bootstrap 4的表格基础类是table,你可以按需搭配table-striped(条纹行)、table-hover(悬停高亮)、table-bordered(边框)、table-dark(深色主题)这些修饰类。

2. 给特定列单独设置样式

如果需要给某一列的表头或数据单元格单独加样式,可在定义列时指定attrs:

class PersonTable(tables.Table):
    # 给表头单元格加table-primary类,数据单元格居中
    name = tables.Column(attrs={"th": {"class": "table-primary"}, "td": {"class": "text-center"}})
    # 给数据单元格加text-muted类(浅灰色文字)
    hardware_type = tables.Column(attrs={"td": {"class": "text-muted"}})

    class Meta:
        model = player_hardware
        template_name = "django_tables2/bootstrap-responsive.html"
        attrs = {"class": "table"}

3. 自定义模板实现更灵活的样式

如果官方的bootstrap-responsive模板满足不了需求,可复制该模板到项目templates目录下,修改模板中的<table>标签部分,手动添加所需类或调整结构。比如修改模板里的表格标签:

<table {% render_table_attrs table.attrs %} class="table table-dark">

内容的提问来源于stack exchange,提问作者Dobbs760

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 18:50:26