Solution for How do I use Signals i Django to Calculate Age based on Date entered, if entered at all?
is Given Below:
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.
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