3

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?

Selcuk
  • 57,004
  • 12
  • 102
  • 110
Micah Pearce
  • 1,805
  • 3
  • 28
  • 61
  • 2
    Is it impossible to do it manually? start_date = models.DateField(default=timezone.now.replace(month=timezone.now.month-1)), or something like this? – Snipper03 Aug 09 '18 at 03:52
  • 1
    @Snipper03 That won't work because `timezone.now` is not a datetime value but a callable, i.e. a reference to a function. – Selcuk Aug 09 '18 at 04:09
  • 1
    Yes right, it's function in django.utils. Then how about launch a function that getting date of a month ago, as a method of model? like get_date_one_month_ago, and call it in the definition area of model. – Snipper03 Aug 09 '18 at 04:27

1 Answers1

10

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

Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • an exact month isn't necessary, 30 days will suffice. If you realyl wanted to do a month then you could get the current month and year and add number of days in that month to it. Thanks, this works for me! – Micah Pearce Aug 09 '18 at 22:52