如何更改 Django 表行的颜色?

How to change color of Django-tables row?

是否可以根据当前对象的值更改行的颜色?

在我的例子中,我有一个从模型 Job 创建的 tableJob 具有属性 delivery。例如,如果 job.delivery 是 'delivered',我想将行的颜色更改为红色。

我唯一想到的就是使用JQuery,但我不确定这是否有点过分。

class MyOrdersTable(tables.Table):
    edit_entries = tables.TemplateColumn(
            '{% if not record.translator %}<a href="/jobs/update/{{record.id}}">Edit Order</a>{% else %} Can\'t edit order, translator has been assigned. {% endif %}')
    price = tables.Column(default='Not Yet',verbose_name='Price')
    translator = tables.Column(default='Not Yet',verbose_name='Translator')
    progress = tables.TemplateColumn('{{record.delivery.get_status_display}}',verbose_name='Progress')

    class Meta:
        model = Job
        attrs = {'class': 'table table-striped table-bordered table-hover', 'width': '70%'}
        fields = (
            'translator', 'short_description', 'language_from', 'language_to', 'level', 'created', 'modified', 'price',
            'progress','edit_entries')
        empty_text = """You haven't order a translation yet. Can we help you?"""

是的,从 django-tables2 v1.2.0 开始,您可以使用 row attributes:

class MyOrdersTable(tables.Table):
    # [...]
    class Meta:
        model = Jub
        row_attrs = {
            'data-delivery': lambda record: record.delivery
        }

这将呈现如下行:

<tr [...] data-delivery="delivered"><td>....</tr>
<tr [...] data-delivery="peding"><td>....</tr>

您可以使用数据属性来定位带有一些 CSS:

的行
tr[data-delivery='deliverd'] {
    background-color: #f2dede;
}