2👍
✅
In this particular case I would store the hex colour code in a field within a model.
In essence:
class Event(models.Model):
ALERT = "alert"
WARNING = "warning"
ERROR = "error"
EVENT_TYPES = (
(ALERT, "Alert"),
(WARNING, "Warning"),
(ERROR, "Error"),
)
YELLOW = "FF6A00"
ORANGE = "FFE800"
RED = "FF0000"
COLOURS = (
(YELLOW, "Yellow"),
(ORANGE, "Orange"),
(RED, "Red"),
)
event_type = models.CharField(max_length=16, choices=EVENT_TYPES, default=ALERT)
event_colour = models.CharField(max_length=6, choices=COLOURS, default=YELLOW)
Additional note, the reason for the “constants” is to make code that uses this model clean and simple.
# example 1
error_events = Event.objects.filter(event_type=Event.ERROR)
# example 2
if my_event.event_type == Event.Error:
# this is an error event
pass
Also, here’s one way you could do it without a colour field on the model:
class Event(models.Model):
ALERT = "alert"
WARNING = "warning"
ERROR = "error"
EVENT_TYPES = (
(ALERT, "Alert"),
(WARNING, "Warning"),
(ERROR, "Error"),
)
# map events to colours
COLOUR = {
ALERT: "FF6A00",
WARNING: "FFE800",
ERROR: "FF0000",
}
event_type = models.CharField(max_length=16, choices=EVENT_TYPES, default=ALERT)
@property
def colour(self):
"""
Return the hexadecimal colour of this event
"""
self.COLOUR[event_type]
# now this would return True
my_error_event.colour == "FF0000"
👤Matt
0👍
There are a couple of ways to do this.
If the color for an event_type needs to be editable, I would store it in the database as a varchar.
If the color is up to you, then I would probably slugify the __unicode__
of event_type and use CSS to target that class. This does present you with a small amount of maintenance, should a new event_type need to be added, but it gives you the separation of concerns.
- [Answered ]-Django – FormView combined with Mixin
- [Answered ]-Zinnia Templates for List and detail view
- [Answered ]-Printing Arabic characters in python/django
Source:stackexchange.com