Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django Python how to implement my custom birth date function in views?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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) 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading