Reputation: 25
I am trying to make a custom user model in django and adding the additional field "last_updated" which is supposed to update the date and time whenever a user makes changes or saves new data.
class User(AbstractUser):
username = None
email = models.EmailField(_('email address'), unique=True)
photo = models.ImageField(upload_to='avatars/', null=True, blank=True)
last_updated = models.DateTimeField(null=True, blank=True) #defining field in the model.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
return self.email
Upvotes: 0
Views: 429
Reputation: 1610
Wouldn't it be easier to use auto_now=True
?
So your model could look like below:
class User(AbstractUser):
username = None
email = models.EmailField(_('email address'), unique=True)
photo = models.ImageField(upload_to='avatars/', null=True, blank=True)
last_updated = models.DateTimeField(auto_now=True) #defining field in the model.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
return self.email
This would help you have lesser code, and use inbuilt functionality of Django.
Upvotes: 1
Reputation: 10116
Have you tried overriding save method of User:
from datetime import datetime
class User(AbstractUser):
# rest of code
def save(self, *args, **kwargs):
self.last_update = datetime.now()
super(User, self).save(*args, **kwargs)
Upvotes: 0