Search code examples
djangodjango-modelsdatefield

Django: Give date field default value of one month from today


In Django, you can have a date field and set the default value to today.

start_date = models.DateField(default=timezone.now, blank=True, null=True)

How do you set the default date to 1 month from today?


Solution

  • You can use any callable as a default value, so that should work:

    from datetime import timedelta
    
    def one_month_from_today():
        return timezone.now() + timedelta(days=30)
    
    class MyModel(models.Model):
        ...
        start_date = models.DateField(default=one_month_from_today, blank=True, null=True)
    

    Note that I used days=30 as timedelta can't add a month to a date value. If you think of it, "one month from today" is a pretty open statement (how do you want it to behave when today is January 31, for example?).