Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django default=timezone.now + delta

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.

like image 411
Nerses Avatar asked Dec 15 '14 19:12

Nerses


People also ask

What is the default time zone setting in Django?

Django's timezone is set to UTC by default.

What is Delta time Django?

Python timedelta class. The timedelta is a class in datetime module that represents duration. The delta means average of difference and so the duration expresses the difference between two date, datetime or time instances.

How do I get the current time in Django?

First, open the views.py file of your Django application and import the datetime module. Next, use the datetime. now() method to get the current date and time value.

What is Use_tz in Django?

When USE_TZ is False, this is the time zone in which Django will store all datetimes. When USE_TZ is True, this is the default time zone that Django will use to display datetimes in templates and to interpret datetimes entered in forms.


1 Answers

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.)

like image 185
Kevin Christopher Henry Avatar answered Oct 05 '22 20:10

Kevin Christopher Henry