首页 > 解决方案 > django-table2 - 根据特定列的值更改整行的背景颜色

问题描述

我一直在尝试使用 django-table2 包突出显示表格的整行。

我设法通过以下方式更改了一条记录的字体颜色:

def render_MyValue(self, value, column, record):
   if record['Warning']:
       column.attrs = {'td': {'style': 'color:darkorange;'}}
   else:
       column.attrs = {'td': {'style': 'color:black;'}}
   return value

在我的表类下面找到:

class DetailedReportTable(tables.Table):
    MyValue = tables.Column(orderable=False, verbose_name='Value')
    ...
    Warning = tables.Column(orderable=False, visible=False)

问题是如果警告为真,我找不到如何将行的背景设置为橙色。

按照此处的文档,我还尝试了以下方法:

class DetailedReportTable(tables.Table):
    ...

    class Meta:
        row_attrs = { "bg-color": lambda record: "#8B0000" if record['Warning'] else "#000000" }

但这无济于事...

如何使用 django-table2 更改行的背景颜色?

标签: djangodjango-tables2

解决方案


您尝试的很接近,但您只是在行 html 元素上设置了“bg-color”属性 - 该属性不存在。相反,您想设置一个可以在 CSS 中设置样式的类,或者直接设置样式属性。这是第二个选项:

class DetailedReportTable(tables.Table):
    ...

    class Meta:
        row_attrs = { "style": lambda record: "background-color: #8B0000;" if record['Warning'] else "background-color: #000000;" }

推荐阅读