开发者

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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜