How to update date automatically after a value change in django?

0 votes

In the following django model:

class MyModel(models.Model):
    published = models.BooleanField(default=False)
    pub_date = models.DateTimeField('date published')

I want the pub_date field to be automatically updated with the current date, every time the published field changes to True.

Any help?

Jul 2 in Python by kartik
• 20,980 points
103 views

1 answer to this question.

0 votes

Hello @kartik,

Only change your pub_date if published has been modified from False to True:

from datetime import datetime

def __init__(self, *args, **kwargs):
    super(MyModel, self).__init__(*args, **kwargs)
    self.old_published = self.published

def save(self, *args, **kwargs):
    if self.published and self.old_published != self.published:
        self.pub_date = datetime.now()
    super(Model, self).save(*args, **kwargs)

Hope it helps!

Thanks!

answered Jul 2 by Niroj
• 44,800 points

Related Questions In Python

+1 vote
2 answers

How to change/update cell value in Python Pandas dataframe?

You can use the at() method to ...READ MORE

answered Apr 8, 2019 in Python by Kunal
66,575 views
0 votes
1 answer

How to hide a window in the constructor immediately after creation?

You can use QtCore.QTimer class Example(QWidget):     def __init__(self, app):         QWidget.__init__(self)         QTimer.singleShot(0, ...READ MORE

answered Apr 17, 2018 in Python by anonymous
88 views
0 votes
1 answer

How to change one character in a string in Python?

Python strings are immutable, you change them ...READ MORE

answered Dec 4, 2018 in Python by Nymeria
• 3,520 points
274 views
0 votes
1 answer

I have a dictonary in python how to access the value field?

dic={"car":["limo","sedan"]} print (dic.keys())    <-----------------------Fetch the key "car" print (dic['car'][0])   <------------------------Fetch ...READ MORE

answered Dec 19, 2018 in Python by Shuvodip
119 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23 in Python by Niroj
• 44,800 points
71 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23 in Python by Niroj
• 44,800 points
44 views
0 votes
1 answer

How to look up a dictionary value with a variable in Django template?

Hii @kartik, Write a custom template filter: from django.template.defaulttags ...READ MORE

answered Aug 3 in Python by Niroj
• 44,800 points
37 views
0 votes
1 answer

How to load a custom JS file in Django admin home?

Hello @kartik, You can override templates/admin/index.html and add the JavaScript ...READ MORE

answered May 14 in Python by Niroj
• 44,800 points
386 views