Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 653
user1261774 Avatar asked Nov 01 '25 19:11

user1261774


1 Answers

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

like image 79
user1261774 Avatar answered Nov 03 '25 09:11

user1261774



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!