سؤال

I'm using django-tables2's {% render_table table %} to display a web page that has a table. The table has multiple rows and columns. Some of the columns have text that spans multiple lines. This creates rows with different heights.

I've tried playing around with the CSS but it doesn't seem to affect the width:

.my_col_2 {
    width: 100px;
}

my views.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})

How do I manually specify the width of columns and height of rows when using django-tables2?

هل كانت مفيدة؟

المحلول

You'll have to choose width and or height as limiting factors for your columns. Assuming you can't dictate the content length, you could choose truncating what is shown.

as shown in Set the table column width constant regardless of the amount of text in its cells? and Using CSS to create table cells of a specific width with no word wrapping , it is hard or impossible to set the table column width directly without fiddling with the table layout and width settings; alternatively, you could wrap every content in a div, and then apply your formatting to those divs.

To achieve this in tables2, I overrode the 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>")

create the column in the table:

    custom_column = DivWrappedColumn(classname='custom_column')

and then apply the css:

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

This results in a fixed-width, fixed height cell that wraps until there are no more rows and then truncates.

Alternatively, use "white-space: nowrap", and omit the height; then the cell is just truncated (but users can scroll).

نصائح أخرى

# 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%;" }}

    
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top