Set background color for a field depending on its value

孤者浪人 提交于 2019-12-22 11:35:35

问题


I have a Customer table and one of the fields here is for Status....I want to have the background colour of the cell containing this field to be set according to it's value e.g green for the status "Closed"; yellow for the status "Pending" and so on.

What's the best way to do this...possibly something that'll be easy to modify if need be in future?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/2834618/set-background-color-for-a-field-depending-on-its-value

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