Set background color for a field depending on its value

ε祈祈猫儿з 提交于 2019-12-06 08:05:58
mmrs151

On your css create class for td as follows, considering you want to display your customer table information in a html table,

td.closed{ color: green; }
td.pending{ color: yellow; }

Now on your template you can loop your database table on your html table and on the td you can call the css as follows:

<td class="{{ status|lower }}">{{ status }}</td>

Hope that helps

Last time i did something like this i had enumerated values for statues that had to be translated to other languages so i could not afford to depend on the string value of status as class in CSS, so i used choices like this:

Define choices in your models.py

class SomeModel(models.Model):
    STATUS_CHOICES = (
       (1, _('Pending')),
       (2, _('Closed')),
    )
    status = models.IntegerField(choices=STATUS_CHOICES)

With HTML looking something like this:

<td class="color_{{ model_instance.status }}">
    {{ model_instance.status.get_status_display }}
</td>

And your CSS should be similar to:

td.color_1{ color: green; }
td.color_2{ color: yellow; }

Basically you could change the status string value without changing CSS, same could be done if the status is enumerated value connected by foreign key for example. There are other ways to do it, but the answer mmrs151 gave is simplest and sufficient in most cases.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!