7👍
You need to do
def age(self):
import datetime
return int((datetime.date.today() - self.birthday).days / 365.25 )
as your birthday is a DateField.
1👍
I think you first defined a method age
and in the next line reassigned the name age
.
Try
def calculate_age(self):
import datetime
return int((datetime.datetime.now() - self.birthday).days / 365.25 )
age = property(calculate_age)
Aside: You can (and should) post the relevant portions of the code here and not expect the others to look up your code on a different site.
- [Django]-ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details
- [Django]-Django AttributeError: 'InterestsForm' object has no attribute '_errors'
- [Django]-Django occasionally throwing a NoReverseMatch
- [Django]-Django data migration – class variable unavailable via get_model()
- [Django]-Best JSON library to get JSON data for Django?
1👍
it will display the age based on your month too.
in models.py
class Profile(models.Model):
date_of_birth = models.DateField()
def age(self):
import datetime
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
in profile.html
<span>Age : </span> <i> {{ profile.age }} </i>
- [Django]-Style Django form error message
- [Django]-How to stop server ran in Daemon mode in Django?
- [Django]-Django REST framework nested serializer and POST nested JSON with files
1👍
You don’t need a model method to calculate age; you can just use the built-in template filter timesince
[link to doc]:
<span>Age: {{ person.age|timesince }}</span>
A downside is that it seems there is currently no way to customize the resulting string if you only want the age in years. For instance, it usually returns the month in addition to years, e.g. “37 years, 2 months”. It can also return strange strings like “65 years, 12 months” (when a birth date is not at least exactly 66 years ago). This filter is not specifically intended for computing a person’s age after all.
- [Django]-Aggregate totals of a ViewSet results in Django Rest Framework
- [Django]-In django allauth, how do I get the username from an OpenId login / Google?
- [Django]-Create method for foreign key relationships with Django Rest Framework serializers
- [Django]-Django custom templatetag not getting request in context