[Django]-Define and insert age in django template

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.

👤jammon

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>

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.

Leave a comment