~pidgeon690/django-registration/patch+remove-sites-dep

« back to all changes in this revision

Viewing changes to registration/forms.py

  • Committer: django
  • Date: 2009-03-21 09:52:44 UTC
  • Revision ID: django@slice.fergusrossferrier.co.uk-20090321095244-wghpv73l1oso26w6
Upstream 221 added. 

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""
 
2
Forms and validation code for user registration.
 
3
 
 
4
"""
 
5
 
 
6
 
 
7
from django.contrib.auth.models import User
 
8
from django import forms
 
9
from django.utils.translation import ugettext_lazy as _
 
10
 
 
11
from registration.models import RegistrationProfile
 
12
 
 
13
 
 
14
# I put this on all required fields, because it's easier to pick up
 
15
# on them with CSS or JavaScript if they have a class of "required"
 
16
# in the HTML. Your mileage may vary. If/when Django ticket #3515
 
17
# lands in trunk, this will no longer be necessary.
 
18
attrs_dict = { 'class': 'required' }
 
19
 
 
20
 
 
21
class RegistrationForm(forms.Form):
 
22
    """
 
23
    Form for registering a new user account.
 
24
    
 
25
    Validates that the requested username is not already in use, and
 
26
    requires the password to be entered twice to catch typos.
 
27
    
 
28
    Subclasses should feel free to add any additional validation they
 
29
    need, but should either preserve the base ``save()`` or implement
 
30
    a ``save()`` method which returns a ``User``.
 
31
    
 
32
    """
 
33
    username = forms.RegexField(regex=r'^\w+$',
 
34
                                max_length=30,
 
35
                                widget=forms.TextInput(attrs=attrs_dict),
 
36
                                label=_(u'username'))
 
37
    email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
 
38
                                                               maxlength=75)),
 
39
                             label=_(u'email address'))
 
40
    password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
 
41
                                label=_(u'password'))
 
42
    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
 
43
                                label=_(u'password (again)'))
 
44
    
 
45
    def clean_username(self):
 
46
        """
 
47
        Validate that the username is alphanumeric and is not already
 
48
        in use.
 
49
        
 
50
        """
 
51
        try:
 
52
            user = User.objects.get(username__iexact=self.cleaned_data['username'])
 
53
        except User.DoesNotExist:
 
54
            return self.cleaned_data['username']
 
55
        raise forms.ValidationError(_(u'This username is already taken. Please choose another.'))
 
56
 
 
57
    def clean(self):
 
58
        """
 
59
        Verifiy that the values entered into the two password fields
 
60
        match. Note that an error here will end up in
 
61
        ``non_field_errors()`` because it doesn't apply to a single
 
62
        field.
 
63
        
 
64
        """
 
65
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
 
66
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
 
67
                raise forms.ValidationError(_(u'You must type the same password each time'))
 
68
        return self.cleaned_data
 
69
    
 
70
    def save(self):
 
71
        """
 
72
        Create the new ``User`` and ``RegistrationProfile``, and
 
73
        returns the ``User`` (by calling
 
74
        ``RegistrationProfile.objects.create_inactive_user()``).
 
75
        
 
76
        """
 
77
        new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'],
 
78
                                                                    password=self.cleaned_data['password1'],
 
79
                                                                    email=self.cleaned_data['email'])
 
80
        return new_user
 
81
 
 
82
 
 
83
class RegistrationFormTermsOfService(RegistrationForm):
 
84
    """
 
85
    Subclass of ``RegistrationForm`` which adds a required checkbox
 
86
    for agreeing to a site's Terms of Service.
 
87
    
 
88
    """
 
89
    tos = forms.BooleanField(widget=forms.CheckboxInput(attrs=attrs_dict),
 
90
                             label=_(u'I have read and agree to the Terms of Service'),
 
91
                             error_messages={ 'required': u"You must agree to the terms to register" })
 
92
 
 
93
 
 
94
class RegistrationFormUniqueEmail(RegistrationForm):
 
95
    """
 
96
    Subclass of ``RegistrationForm`` which enforces uniqueness of
 
97
    email addresses.
 
98
    
 
99
    """
 
100
    def clean_email(self):
 
101
        """
 
102
        Validate that the supplied email address is unique for the
 
103
        site.
 
104
        
 
105
        """
 
106
        if User.objects.filter(email__iexact=self.cleaned_data['email']):
 
107
            raise forms.ValidationError(_(u'This email address is already in use. Please supply a different email address.'))
 
108
        return self.cleaned_data['email']
 
109
 
 
110
 
 
111
class RegistrationFormNoFreeEmail(RegistrationForm):
 
112
    """
 
113
    Subclass of ``RegistrationForm`` which disallows registration with
 
114
    email addresses from popular free webmail services; moderately
 
115
    useful for preventing automated spam registrations.
 
116
    
 
117
    To change the list of banned domains, subclass this form and
 
118
    override the attribute ``bad_domains``.
 
119
    
 
120
    """
 
121
    bad_domains = ['aim.com', 'aol.com', 'email.com', 'gmail.com',
 
122
                   'googlemail.com', 'hotmail.com', 'hushmail.com',
 
123
                   'msn.com', 'mail.ru', 'mailinator.com', 'live.com']
 
124
    
 
125
    def clean_email(self):
 
126
        """
 
127
        Check the supplied email address against a list of known free
 
128
        webmail domains.
 
129
        
 
130
        """
 
131
        email_domain = self.cleaned_data['email'].split('@')[1]
 
132
        if email_domain in self.bad_domains:
 
133
            raise forms.ValidationError(_(u'Registration using free email addresses is prohibited. Please supply a different email address.'))
 
134
        return self.cleaned_data['email']