Source code for registration.forms
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Forms of django-inspectional-registration
This is a modification of django-registration_ ``forms.py``
The original code is written by James Bennett
.. _django-registration: https://bitbucket.org/ubernostrum/django-registration
Original License::
Copyright (c) 2007-2011, James Bennett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the author nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
__author__ = 'Alisue <lambdalisue@hashnote.net>'
__all__ = (
'ActivationForm', 'RegistrationForm',
'RegistrationFormNoFreeEmail',
'RegistrationFormTermsOfService',
'RegistrationFormUniqueEmail',
)
from django import forms
from django.utils.translation import ugettext_lazy as _
from registration.compat import get_user_model
attrs_dict = {'class': 'required'}
[docs]class ActivationForm(forms.Form):
"""Form for activating a user account.
Requires the password to be entered twice to catch typos.
Subclasses should feel free to add any additional validation they need, but
should avoid defining a ``save()`` method -- the actual saving of collected
user data is delegated to the active registration backend.
"""
password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict,
render_value=False),
label=_("Password"))
password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict,
render_value=False),
label=_("Password (again)"))
[docs] def clean(self):
"""Check the passed two password are equal
Verifiy that the values entered into the two password fields match.
Note that an error here will end up in ``non_field_errors()`` because it
doesn't apply to a single field.
"""
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError(_("The two password fields didn't match."))
return self.cleaned_data
[docs]class RegistrationForm(forms.Form):
"""Form for registration a user account.
Validates that the requested username is not already in use, and requires
the email to be entered twice to catch typos.
Subclasses should feel free to add any additional validation they need, but
should avoid defining a ``save()`` method -- the actual saving of collected
user data is delegated to the active registration backend.
"""
username = forms.RegexField(regex=r'^[\w.@+-]+$',
max_length=30,
widget=forms.TextInput(attrs=attrs_dict),
label=_("Username"),
error_messages={
'invalid': _("This value must contain "
"only letters, numbers and "
"underscores.")
})
email1 = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
maxlength=75)),
label=_("E-mail"))
email2 = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
maxlength=75)),
label=_("E-mail (again)"))
[docs] def clean_username(self):
"""
Validate that the username is alphanumeric and is not already in use.
"""
User = get_user_model()
try:
User.objects.get(username__iexact=self.cleaned_data['username'])
except User.DoesNotExist:
return self.cleaned_data['username']
raise forms.ValidationError(_(
"A user with that username already exists."))
[docs] def clean(self):
"""Check the passed two email are equal
Verifiy that the values entered into the two email fields match.
Note that an error here will end up in ``non_field_errors()`` because
it doesn't apply to a single field.
"""
if 'email1' in self.cleaned_data and 'email2' in self.cleaned_data:
if self.cleaned_data['email1'] != self.cleaned_data['email2']:
raise forms.ValidationError(_(
"The two email fields didn't match."))
return self.cleaned_data
[docs]class RegistrationFormTermsOfService(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which adds a required checkbox for
agreeing to a site's Terms of Service.
"""
tos = forms.BooleanField(widget=forms.CheckboxInput(attrs=attrs_dict),
label=_('I have read and agree to the Terms '
'of Service'),
error_messages={'required': _(
"You must agree to the terms to register")})
[docs]class RegistrationFormUniqueEmail(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which enforces uniqueness of email address
"""
[docs] def clean_email1(self):
"""Validate that the supplied email address is unique for the site."""
User = get_user_model()
if User.objects.filter(email__iexact=self.cleaned_data['email1']):
raise forms.ValidationError(_(
"This email address is already in use. "
"Please supply a different email address."))
return self.cleaned_data['email1']
[docs]class RegistrationFormNoFreeEmail(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which disallows registration with email
addresses from popular free webmail services; moderately useful for
preventing automated spam registration.
To change the list of banned domains, subclass this form and override the
attribute ``bad_domains``.
"""
bad_domains = ['aim.com', 'aol.com', 'email.com', 'gmail.com',
'googlemail.com', 'hotmail.com', 'hushmail.com',
'msn.com', 'mail.ru', 'mailinator.com', 'live.com',
'yahoo.com']
[docs] def clean_email1(self):
"""
Check the supplied email address against a list of known free webmail
domains.
"""
email_domain = self.cleaned_data['email1'].split('@')[1]
if email_domain in self.bad_domains:
raise forms.ValidationError(_(
"Registration using free email addresses is prohibited. "
"Please supply a different email address."))
return self.cleaned_data['email1']