Django:如何更改 django-tables2 中的列宽

问题描述 投票:0回答:2

我正在使用

django-tables2
{% render_table table %}
来显示包含表格的网页。该表有多个行和列。有些列的文本跨多行。这会创建具有不同高度的行。

我尝试过使用 CSS,但它似乎并没有影响宽度:

.my_col_2 {
    width: 100px;
}

我的观点.py:

def index(request):
    table = OrderTable(Order.objects.all(), order_by="-order_date")
    RequestConfig(request, paginate={"per_page": 10}).configure(table)
    return render(request, 'orders_app/index.html', {'table': table})

使用 django-tables2 时如何手动指定列宽和行高?

django python-2.7 django-tables2
2个回答
4
投票

您必须选择宽度和/或高度作为列的限制因素。假设您无法指定内容长度,您可以选择截断显示的内容。

如图所示 无论单元格中的文本量如何,都将表格列宽设置为常量?使用 CSS 创建特定宽度的表格单元格且不自动换行 ,在不摆弄表格布局和宽度设置的情况下,很难或不可能直接设置表格列宽;或者,您可以将所有内容包装在一个 div 中,然后将格式应用于这些 div。

为了在tables2中实现这一点,我覆盖了table.Column:

class DivWrappedColumn(tables.Column):

    def __init__(self, classname=None, *args, **kwargs):
        self.classname=classname
        super(DivWrappedColumn, self).__init__(*args, **kwargs)

    def render(self, value):
        return mark_safe("<div class='" + self.classname + "' >" +value+"</div>")

在表中创建列:

    custom_column = DivWrappedColumn(classname='custom_column')

然后应用CSS:

div.custom_column {
  white-space: normal;
  width: 200px;
  height: 45px;
}

这会产生一个固定宽度、固定高度的单元格,该单元格会换行,直到没有更多行,然后截断。

或者,使用“white-space: nowrap”,并省略高度;那么单元格就会被截断(但用户可以滚动)。


2
投票
# assume columns c1 and c2 that should be only as wide as needed
#   to fit their content
# and a column c3 which takes up the rest of the table width 

class MyTable(tables.Table):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.columns['c1'].column.attrs = {"td":{"style" : "width:1%;" }}
        self.columns['c2'].column.attrs = {"td":{"style" : "width:1%;" }}

    
© www.soinside.com 2019 - 2024. All rights reserved.