在Django Tables 2中可以使用colspan吗?

0 投票
1 回答
1606 浏览
提问于 2025-04-18 03:22

在Django的表格2中,可以使用colspan吗?我有5行4列的表格,但我想让第二行合并成1列,也就是colspan=4。

我该怎么做呢?这是可能的吗?

这是我的代码:

class FavoriteContactTable(FavoriteTable):
    date_added = tables.Column()
    address = AddressColumn(empty_values=(), orderable=False)
    email = tables.EmailColumn(accessor='swimmer.user.email')
    phone = PhoneColumn(empty_values=())

    class Meta:
        model = Favorite
        fields = ('address', 'email', 'phone', 'date_added')
        attrs = {"class": "table table-condensed table-striped table-hover"}

1 个回答

0

可以给一个 Column 添加 colspan,方法是:

tables.Column(attrs={"td": {"colspan": "4"}})

不过,这样做会让这个列的所有行都跨越4个单元格,而不仅仅是第二行。

另一种解决办法是重写表格模板:

class FavoriteContactTable(FavoriteTable):
    template = "path_to_template"

你需要扩展 django_tables2/table.html 模板,然后重写 table.tbody.row 这个部分。

可能最简单的办法是用 jQuery 或 Javascript 来实现。

$(document).ready(function() {
    $(".table > tbody > tr:nth-child(2) > td:nth-child(column_no)").attr("colspan", "4");
});

我没有检查过 Javascript,但应该是类似这样的内容。

撰写回答