How to change color of Django-tables row?

2020-07-22 19:37发布

问题:

is it possible to change a color of row based on current object's value?

In my case, I have a table created from model Job. The Job has attribute delivery. If job.delivery is for example 'delivered', I want to change the color of the row to red.

The only thing comes to my mind is to use JQuery but I'm not sure if it is not an overkill.

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?"""

回答1:

Yes it is, as of django-tables2 v1.2.0 you can use row attributes:

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

This will render rows like this:

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

You can use the data attribute to target the row with some CSS:

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