问题
Trying to set a timestamp for a key expiration in Django model and bumped into this issue :
My current code :
key_expires = models.DateTimeField(default=timezone.now() + timezone.timedelta(days=1))
The code above works, however when "timezone.now()" is used, it gets the timestamp form the time when Apache was restarted, so this doesn't work. I did some research and found the solution for that part of the issue, so by replacing "timezone.now()" with "timezone.now", I'm getting the current time stamp every time the object is created, which is perfect, issue is partially solved.
I'm having trouble changing the date by using the "timezone.timedelta(days=1)".
key_expires = models.DateTimeField(default=timezone.now + timezone.timedelta(days=1))
Error I'm getting is :
key_expires = models.DateTimeField(default=timezone.now + timezone.timedelta(days=1))
TypeError: unsupported operand type(s) for +: 'function' and 'datetime.timedelta'
The goal is to set the time stamp 24 hours ahead.
Any help is greatly appreciated.
回答1:
default
takes a callable, so you just need to write a function to do what you want and then provide that as the argument:
def one_day_hence():
return timezone.now() + timezone.timedelta(days=1)
class MyModel(models.Model):
...
key_expires = models.DateTimeField(default=one_day_hence)
(As discussed here, resist the temptation to make this a lambda
.)
回答2:
I'm working on django 2.1.7, In this version it doesn't required to write a function for default
. You can simply use your by simple modification of your previous code, which is:
key_expires = models.DateTimeField(default=timezone.now() + timezone.timedelta(days=1))
If you notice the difference is ()
after timezone.now
You can follow the link for more information about timedelta
来源:https://stackoverflow.com/questions/27491248/django-default-timezone-now-delta