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?
Asked
Active
Viewed 4,385 times
2 Answers
10
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

Trey Hunner
- 10,975
- 4
- 55
- 114
-
1Thanks, note you have bod.day instead of dob.day . too small a change to edit – sidarcy Feb 27 '14 at 10:12
6
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.

rz.
- 19,861
- 10
- 54
- 47
-
Perfect! Only problem with the example is that you can't subtract a date from a datetime but this got me where I needed to be. Thanks. – Dave Forgac Dec 14 '10 at 05:49
-