PageRenderTime 59ms CodeModel.GetById 48ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/registration/forms.py

https://bitbucket.org/andrewlvov/django-registration-custom
Python | 120 lines | 100 code | 5 blank | 15 comment | 4 complexity | e6108465f0535ab954ba622e8e7c8391 MD5 | raw file
  1"""
  2Forms and validation code for user registration.
  3
  4Note that all of these forms assume Django's bundle default ``User``
  5model; since it's not possible for a form to anticipate in advance the
  6needs of custom user models, you will need to write your own forms if
  7you're using a custom model.
  8
  9"""
 10
 11
 12from django.contrib.auth.models import User
 13from django import forms
 14from django.utils.translation import ugettext_lazy as _
 15
 16
 17class RegistrationForm(forms.Form):
 18    """
 19    Form for registering a new user account.
 20    
 21    Validates that the requested username is not already in use, and
 22    requires the password to be entered twice to catch typos.
 23    
 24    Subclasses should feel free to add any additional validation they
 25    need, but should avoid defining a ``save()`` method -- the actual
 26    saving of collected user data is delegated to the active
 27    registration backend.
 28
 29    """
 30    required_css_class = 'required'
 31    
 32    username = forms.RegexField(regex=r'^[\w.@+-]+$',
 33                                max_length=30,
 34                                label=_("Username"),
 35                                error_messages={'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
 36    email = forms.EmailField(label=_("E-mail"))
 37    password1 = forms.CharField(widget=forms.PasswordInput,
 38                                label=_("Password"))
 39    password2 = forms.CharField(widget=forms.PasswordInput,
 40                                label=_("Password (again)"))
 41    
 42    def clean_username(self):
 43        """
 44        Validate that the username is alphanumeric and is not already
 45        in use.
 46        
 47        """
 48        existing = User.objects.filter(username__iexact=self.cleaned_data['username'])
 49        if existing.exists():
 50            raise forms.ValidationError(_("A user with that username already exists."))
 51        else:
 52            return self.cleaned_data['username']
 53
 54    def clean(self):
 55        """
 56        Verifiy that the values entered into the two password fields
 57        match. Note that an error here will end up in
 58        ``non_field_errors()`` because it doesn't apply to a single
 59        field.
 60        
 61        """
 62        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
 63            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
 64                raise forms.ValidationError(_("The two password fields didn't match."))
 65        return self.cleaned_data
 66
 67
 68class RegistrationFormTermsOfService(RegistrationForm):
 69    """
 70    Subclass of ``RegistrationForm`` which adds a required checkbox
 71    for agreeing to a site's Terms of Service.
 72    
 73    """
 74    tos = forms.BooleanField(widget=forms.CheckboxInput,
 75                             label=_(u'I have read and agree to the Terms of Service'),
 76                             error_messages={'required': _("You must agree to the terms to register")})
 77
 78
 79class RegistrationFormUniqueEmail(RegistrationForm):
 80    """
 81    Subclass of ``RegistrationForm`` which enforces uniqueness of
 82    email addresses.
 83    
 84    """
 85    def clean_email(self):
 86        """
 87        Validate that the supplied email address is unique for the
 88        site.
 89        
 90        """
 91        if User.objects.filter(email__iexact=self.cleaned_data['email']):
 92            raise forms.ValidationError(_("This email address is already in use. Please supply a different email address."))
 93        return self.cleaned_data['email']
 94
 95
 96class RegistrationFormNoFreeEmail(RegistrationForm):
 97    """
 98    Subclass of ``RegistrationForm`` which disallows registration with
 99    email addresses from popular free webmail services; moderately
100    useful for preventing automated spam registrations.
101    
102    To change the list of banned domains, subclass this form and
103    override the attribute ``bad_domains``.
104    
105    """
106    bad_domains = ['aim.com', 'aol.com', 'email.com', 'gmail.com',
107                   'googlemail.com', 'hotmail.com', 'hushmail.com',
108                   'msn.com', 'mail.ru', 'mailinator.com', 'live.com',
109                   'yahoo.com']
110    
111    def clean_email(self):
112        """
113        Check the supplied email address against a list of known free
114        webmail domains.
115        
116        """
117        email_domain = self.cleaned_data['email'].split('@')[1]
118        if email_domain in self.bad_domains:
119            raise forms.ValidationError(_("Registration using free email addresses is prohibited. Please supply a different email address."))
120        return self.cleaned_data['email']