user1261774
user1261774

Reputation: 3695

django-admin: change column font to red when if condition is true

I have a vlog that I can preload vlog entries into the db, so that when the date of vlog-published-date is less than the models field of now, the vlog entry will be automatically displayed / published.

How can I make the django-admin column of Vlog Date Published font red when the date of the vlog_published_date is greater than now (not yet published)?

Here is a visual example of what I mean where the now date is January 16, 2018:

enter image description here

Here is my vlog models.py code:

class VlogDetails(models.Model):
    ....
    vlog_date_published = models.DateField(null=False, blank=False, default=datetime.now, help_text='The date the vlog video will be made public.')
    ....

    class Meta:
        ....

There is this similar thread, but the thread is 7+ years old and I was hoping there was information more current to django 1.10 and python 3.5.

Upvotes: 4

Views: 1505

Answers (1)

user1261774
user1261774

Reputation: 3695

Here is the answer - I hope that this helps somone!

This is my models.py code:

class VlogDetails(models.Model):
    ....
    vlog_date_published = models.DateField(null=False, blank=False, default=datetime.now, help_text='The date the vlog video will be made public.')
    ....

    # date published replaces vlog_date_published in the admin - displays red date when vlog not published.
    def date_published(self):
        if self.vlog_date_published > datetime.today().date():
            return format_html('<span style="color: #cc0033; font-weight: bold;">{0}</span>', self.vlog_date_published.strftime('%b. %d, %Y'))
        else:
            return format_html('<span style="color: #000;">{0}</span>', self.vlog_date_published.strftime('%b. %d, %Y'))

    date_published.allow_tags = True

    class Meta:
        ....

Here is my admin.py code:

list_display = [
    u'id',
    #'vlog_date_published', # vlog_date_published now replaced by date_published.
    'date_published',
    'vlog_title',
    ....
]

This is the visual representation:

enter image description here

Upvotes: 6

Related Questions