Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Django model date field default value to future date?

I'm trying to set the default value for a Date field to a future date with respect to today. However, it gives me the following warning when I set it as below.

return_date = models.DateField(default=(timezone.now() + timedelta(days=1)))

booking.Booking.return_date: (fields.W161) Fixed default value provided.
HINT: It seems you set a fixed date / time / datetime value as default for 
this field. This may not be what you want. If you want to have the 
current date as default, use `django.utils.timezone.now`

Same warning with the following code.

return_date = models.DateField(default=(date.today() + timedelta(days=1)))

What is the correct way to do this?

Thanks.

like image 255
Indika Rajapaksha Avatar asked Aug 22 '18 15:08

Indika Rajapaksha


1 Answers

You are giving it a fixed time(cause you are calling the timezone.now() so its returned value will be the default) you should pass the function to the default without calling it, like this

def return_date_time():
    now = timezone.now()
    return now + timedelta(days=1)

and in your field:

return_date = models.DateField(default=return_date_time) 
### dont call it, so it will be evaluated by djanog when creating an instance
like image 163
Ehsan Nouri Avatar answered Oct 13 '22 13:10

Ehsan Nouri