Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add age verification to a django-registration form?

I have a Django application that is using django-registration to handle new user registration. I would like to add date of birth to the registration form so that I can check the user's age before deciding whether to allow them to register. However I don't need or even want to store their date of birth as profile information. How can I add this to the registration form and validate their age as part of the registration process?

like image 380
Dave Forgac Avatar asked Dec 13 '10 20:12

Dave Forgac


1 Answers

There is a minor flaw in rz's answer in that it doesn't take into account leap years.

If someone is born on January 1, 1994 the birthdate check mentioned in rz's answer will calculate them as being 18 on December 28, 2011.

Here's an alternate version that takes leap years into account:

from datetime import date
from registration.forms import RegistrationForm

class DOBRegistrationForm(RegistrationForm):
    date_of_birth = forms.DateField()

    def clean_date_of_birth(self):
        dob = self.cleaned_data['date_of_birth']
        today = date.today()
        if (dob.year + 18, dob.month, bod.day) > (today.year, today.month, today.day):
            raise forms.ValidationError('Must be at least 18 years old to register')
        return dob
like image 111
Trey Hunner Avatar answered Oct 26 '22 22:10

Trey Hunner