views:

51

answers:

4

This code:

import datetime
d_tomorrow = datetime.date.today() + datetime.timedelta(days=1)

class Model(models.Model):
    ...
    timeout = models.DateTimeField(null=True, blank=True, default=d_tomorrow)
    ...

resuls in this error:

'datetime.date' object has no attribute 'date'

What am I doing wrong?

A: 

This works for me:

import datetime
from datetime import timedelta

tomorrow = datetime.date.today() + timedelta(days=1)

class Test(models.Model):
    timeout = models.DateTimeField(db_index=True, default=tomorrow)

Alternatively you could use tomorrow = datetime.datetime.now() + timedelta(days=1)

the_void
Still, same error. And no, I can't use that, since I don't want the time.
Arnar Yngvason
A: 

I tried out your code and it worked just fine. Can you verify that you are not modifying/redefining the import in some way?

Also try this:

import datetime as DT
d_tomorrow = DT.date.today() + DT.timedelta(days=1)

class Model(models.Model):
    timeout = models.DateTimeField(null=True, blank=True, default=d_tomorrow)
Manoj Govindan
-1: Duplicate of what the_void answered
Andrew Sledge
I fail to see how it is a duplicate for two reasons. (1) I asked a legitimate question/tip about imports getting redefined. (2) the code snippet I gave is not the same.
Manoj Govindan
+3  A: 

d_tomorrow is expected, by the Django ORM, to have a date attribute (apparently), but doesn't.

At any rate, you probably want to use a callable for the default date; otherwise, every model's default date will be "tomorrow" relative to the time the model class was initialized, not the time that the model is created. You might try this:

import datetime

def tomorrow():
  return datetime.date.today() + datetime.timedelta(days=1)

class Model(models.Model):
  timeout = models.DateTimeField(null=True, blank=True, default=tomorrow)
mipadi
Makes sense. +1.
Manoj Govindan
Thanks, this was helpful. +1
Arnar Yngvason
A: 

Problem solved:

from datetime import datetime, time, date, timedelta
def tomorrow():
    d = date.today() + timedelta(days=1)
    t = time(0, 0)
    return datetime.combine(d, t)
Arnar Yngvason