【问题标题】:Django: How to change the column width in django-tables2Django:如何更改 django-tables2 中的列宽
【发布时间】:2013-11-19 18:33:20
【问题描述】:

我正在使用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


    【解决方案1】:

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

    如图所示 Set the table column width constant regardless of the amount of text in its cells?Using CSS to create table cells of a specific width with no word wrapping ,如果不摆弄表格布局和宽度设置,很难或不可能直接设置表格列宽;或者,您可以将每个内容包装在一个 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):
              self.columns['c1'].column.attrs = {"td":{"style" : "width:1%;" }}
              self.columns['c2'].column.attrs = {"td":{"style" : "width:1%;" }}
      
          
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-23
        • 1970-01-01
        相关资源
        最近更新 更多