'How do I use Signals i Django to Calculate Age based on Date entered, if entered at all?
We do not use Date of Birth as a mandatory field during signup. But, in the Model we have an auto-calculate function to arrive at the 'Age' of the user.
So while this works fine when using Django built-in registration mechanism, it fails with custom.
How can Signals be leveraged to check -
- if DoB was entered?
- if DoB entered, then calculate Age and Populate Age Field?
Thanks in Advance for shring your knowledge.
Regds.
Solution 1:[1]
Storing the age in a field looks like a bad idea: if the record is not updated somehow, or the signals do not run, then the age can get outdated. For example a person might be stored in the database, but if you never save that object again, after the person's birthday, it will still show the old age.
Therefore it is better not to store this in a field, and use for example a property to determine this when that is necessary, you can define such model with:
from django.utils.timezone import now
class User(models.Model):
# …
date_of_birth = models.DateField()
# no age or is_adult field
@property
def age(self):
today = now().date()
dob = self.date_of_birth
return today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))
@property
def is_adult(self):
return self.age >= 18
This will thus make it possible to access .age and .is_adult for a User object.
Solution 2:[2]
Use this.
if instance.dateBirth:
today = date.today()
rdelta = relativedelta(today,instance.dateBirth)
instance.Age = rdelta.years
if instance.Age > 18: #timedelta(days=18 * 365):
instance.is_adult = True
return(instance.is_adult, instance.Age)
else:
instance.is_adult = False
return (instance.is_adult, instance.Age)
dont forget to update __init__.py and apps.py
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
