Search code examples
djangodjango-tables2

django-table2 - Change background color for entire row depending on the value of specific column


I have been trying to highlight an entire row of a table with django-table2 package.

I managed to change font color of one record doing the below:

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

Find below my table class:

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

The problem is I cannot find how to set the background of the row in orange if Warning is True.

Following the doc here I tried also the below:

class DetailedReportTable(tables.Table):
    ...

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

But this is doing nothing...

How can you change background color for a row using django-table2 ?


Solution

  • What you've tried is close, but you're just setting an attribute of "bg-color" on the row html element - that attribute doesn't exist. Instead, you want to set either a class, which you can style in CSS, or directly set a style attribute. Here's the second option:

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