4

How to display age from dob obtained? Any suggestion?

models.py

from django.db import models
import datetime

dob = models.DateField(max_length=8)
age = models.IntegerField() 
def __str__(self):
    today = date.today()
        age = today.year - dob.year
    if today.month < dob.month or today.month == dob.month and today.day < dob.day:
        age -= 1
    return self.age 

Thank you, Rads

Rads
  • 253
  • 1
  • 6
  • 13

2 Answers2

8

You should use the python-dateutil to get the relativedelta between dates:

from dateutil.relativedelta import relativedelta
from django.db import models

dob = models.DateField(max_length=8)
age = models.IntegerField() 
def __str__(self):
    today = date.today()
    delta = relativedelta(today, self.dob)
    return str(delta.years)
mipadi
  • 398,885
  • 90
  • 523
  • 479
1

With the date of birth calculation taken from here, you could put this function on your model. You wouldn't need to store age in the database.

from datetime import date
from django.db import models


class Person(models.Model):
    dob = models.DateField()

    def calculate_age(self):
        today = date.today()

        try: 
            birthday = self.dob.replace(year=today.year)
        # raised when birth date is February 29 and the current year is not a leap year
        except ValueError:
            birthday = self.dob.replace(year=today.year, day=born.day-1)

        if birthday > today:
            return today.year - born.year - 1
        else:
            return today.year - born.year
Community
  • 1
  • 1
Scott Woodall
  • 10,456
  • 6
  • 39
  • 37
  • Hi Scott, Let me get this right, so the age is calculated and is displayed when the Submit is activated right? or is it possible to populate the age when the user selects dob? – Rads Mar 06 '14 at 03:22