Question

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?

Was it helpful?

Solution

Extend the built-in registration form to add the DOB field and a clean_ method to validate that it is before a certain time. Something like:

from datetime import datetime
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']
        age = (datetime.now() - dob).days/365
        if age < 18:
            raise forms.ValidationError('Must be at least 18 years old to register')
        return dob

In your views you use DOBRegistrationForm just like you would the normal RegistrationForm. If you are using the registration.views.register just pass the class as the form_class parameter.

This way they'll get a form error if their DOB is not in the allowed range without creating any rows in the database.

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top