Home > Back-end >  Django Python how to implement my custom birth date function in views?
Django Python how to implement my custom birth date function in views?

Time:01-03

I write this python function for calculate age.

def age(birthdate):
    today = date.today()
    age = today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))
    return age

result:

>>> print(age(date(1980, 1, 1)))
42

here is my code:

models.py

class CalculateAge(models.Model):
      age = models.IntegerField(max_length=100)
      date_of_birth = models.DateField()

user only pick the date of birth and I want age will be automatically calculate when submitting forms.

views.py

def CalculateAge(request):
    if request.method == "POST":
       patient_from = AddPatientFrom(request.POST or None)
       if patient_from.is_valid(): 
          patient_from.save()
      

how to implement this age function in my views.py and models.py?

I tried this in my views.py but didn't work.

if patient_from.is_valid(): 
      pick_date = request.POST['date_of_birth']
      find_age = age(date(pick_date))
      print(find_age) 

getting this error:

TypeError at /add-patient/ an integer is required (got type str)

CodePudding user response:

You should work with the .cleaned_data [Django-doc] of the form: this will contain the data as date object:

if patient_from.is_valid(): 
      pick_date = form.cleaned_data['date_of_birth']
      find_age = age(age_y)
      print(find_age) 
  • Related