How to add age registration to django registration form?

I have a Django application that uses django-registration to handle a new user registration. I would like to add the date of birth to the registration form so that I can check the age of the user before deciding whether to allow them to register. However, I do not need or even want to save the date of birth as profile information. How can I add this to the registration form and confirm my age as part of the registration process?

+4
source share
2 answers

Extend the built-in registration form to add the DOB field and the clean_ method to confirm that it is up to a certain time. Sort of:

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 the DOBRegistrationForm in the same way as a regular RegistrationForm . If you use registration.views.register , just pass the class as the form_class parameter.

Thus, they will get a form error if their DOB is not in the valid range without creating any rows in the database.

+5
source

There is a slight flaw in the rz answer as it does not account for leap years.

If someone was born on January 1, 1994, then checking the date of birth mentioned in the rz answer will calculate them as December 18 to December 28, 2011.

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

 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 
+8
source

All Articles