Reputation: 1199
I want to get the "age" of a user account in my Django app. This is what I did:
class UserData(models.Model):
user = models.ForeignKey(User,unique=True)
birth = models.IntegerField(default=1900)
gender = models.CharField(max_length=1)
@property
def isNew(self):
if (datetime.datetime.now()-self.user.date_joined) < datetime.timedelta(days=40):
return True;
else:
return False;
In my template there is a different view depending on the output of this function. But there is basically NO output.
When simply "printing" the output there is simply nothing returned. When returning the "datetime" and the "date_joined" the date is shown. When returning str(type()) of both "datetime.datetime" is returned. But when returning the difference (or the type of the difference) there is absolutely NOTHING returned. When doing the same in my python console there is a timedelta returned - exactly what I expect.
Any idea where to search next? I can't figure out what's happening to completely prevent this function from giving any output without crashing the app.
Upvotes: 2
Views: 90
Reputation: 9694
You are trying to substract offset-naive and offset-aware datetimes.
You need to install pytz pip install pytz
and change your method with the following:
import datetime, pytz
@property
def isNew(self):
return pytz.utc.localize(datetime.datetime.now())-self.user.date_joined < datetime.timedelta(days=40)
Upvotes: 1
Reputation: 64
You can simply do:
@property
def isNew(self):
return (
datetime.datetime.now() - self.user.date_joined <
datetime.timedelta(days=40)
)
Problem in your code was
return False
as first line of your property so it always returned false.
Moreover you should not use semicolon in python
Upvotes: 0