Reputation: 67
So every time I try to view someone's profile when they haven't entered a birth day I get this error 'NoneType' object has no attribute 'year'
. I followed this post to add the birthday/age to the user profile so no reason to include my code since I got it from here https://stackoverflow.com/a/39761072/12229283.
I tried adding a default
to the model but that doesn't seem to work how do I make it so if a user doesn't enter a birthday just skip it and ignore it? Thanks
Upvotes: 0
Views: 696
Reputation: 1135
I had this issue in the admin>LogEntry after Django upgrade to 3.2.4. The issue was in using date_hierarchy
.
Upvotes: 0
Reputation: 461
You need to add an if / else to the return statement in your age method.
If there is no value for date_of_birth (i.e. it is set to None), you will get that error as you are calling dob.year, where dob = date_of_birth = None.
class Profile(models.Model):
date_of_birth = models.DateField()
def age(self):
import datetime
if self.date_of_birth:
dob = self.date_of_birth
tod = datetime.date.today()
my_age = (tod.year - dob.year) - int((tod.month, tod.day) < (dob.month, dob.day))
return my_age
else:
return ''
Upvotes: 1