Set background color for a field depending on its value
I have a Customer
table and one of the fields h开发者_运维知识库ere 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?
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.
精彩评论