What is the correct way to do conditional formatting in Django?
I have a model that contains a date field, and I would like to display a list of records, but the color of the rows depends on the value of this date field. For example, records that correspond to today's date, I want to be yellow, records that exist until today, I want green and one after I want red.
Somewhere in Django you will need to do this comparison by comparing the current date with the date of recording.
I see three different places that could be compared:
- Add a method to my model, for example status (), which returns either "past", "present", "future", and then uses this in the template to color the strings.
- In the view, instead of returning a set of queries to the template, pre-process the list and compare each record, build a new dict containing the "past", "present" and "future" values ββthat will be used in the template
- Create a new template tag that performs the comparison.
Which of these methods is the correct way for Django? It seems like conditional formatting is something that would happen quite often, and since you cannot make arbitrary comparisons in a template, a different solution is needed.
The same applies to simpler formatting rules, for example, if I wanted to display a list of student grades, and I would like to make them more than 80% green, and those below 30% red.
python django formatting django-templates
Andre Miller
source share