Django

Code

root/django/branches/newforms-admin/django/contrib/auth/forms.py

Revision 7450, 7.6 kB (checked in by brosner, 7 months ago)

newforms-admin: Fixed a typo that should read "E-mail" and not "Email" per the guidelines.

  • Property svn:eol-style set to native
  • Property svn:keywords set to LastChangedRevision
Line 
1 from django.contrib.auth.models import User
2 from django.contrib.auth import authenticate
3 from django.contrib.sites.models import Site
4 from django.template import Context, loader
5 from django.core import validators
6 from django import newforms as forms
7 from django.utils.translation import ugettext_lazy as _
8
9 class UserCreationForm(forms.ModelForm):
10     """
11     A form that creates a user, with no privileges, from the given username and password.
12     """
13     username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^\w+$',
14         help_text = _("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)."),
15         error_message = _("This value must contain only letters, numbers and underscores."))
16     password1 = forms.CharField(label=_("Password"), max_length=60, widget=forms.PasswordInput)
17     password2 = forms.CharField(label=_("Password confirmation"), max_length=60, widget=forms.PasswordInput)
18    
19     class Meta:
20         model = User
21         fields = ("username",)
22    
23     def clean_username(self):
24         username = self.cleaned_data["username"]
25         try:
26             User.objects.get(username=username)
27         except User.DoesNotExist:
28             return username
29         raise forms.ValidationError(_("A user with that username already exists."))
30    
31     def clean_password2(self):
32         password1 = self.cleaned_data["password1"]
33         password2 = self.cleaned_data["password2"]
34         if password1 != password2:
35             raise forms.ValidationError(_("The two password fields didn't match."))
36         return password2
37    
38     def save(self, commit=True):
39         user = super(UserCreationForm, self).save(commit=False)
40         user.set_password(self.cleaned_data["password1"])
41         if commit:
42             user.save()
43         return user
44
45 class AuthenticationForm(forms.Form):
46     """
47     Base class for authenticating users. Extend this to get a form that accepts
48     username/password logins.
49     """
50     username = forms.CharField(label=_("Username"), max_length=30)
51     password = forms.CharField(label=_("Password"), max_length=30, widget=forms.PasswordInput)
52    
53     def __init__(self, request=None, *args, **kwargs):
54         """
55         If request is passed in, the form will validate that cookies are
56         enabled. Note that the request (a HttpRequest object) must have set a
57         cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
58         running this validation.
59         """
60         self.request = request
61         self.user_cache = None
62         super(AuthenticationForm, self).__init__(*args, **kwargs)
63    
64     def clean(self):
65         username = self.cleaned_data.get('username')
66         password = self.cleaned_data.get('password')
67        
68         if username and password:
69             self.user_cache = authenticate(username=username, password=password)
70             if self.user_cache is None:
71                 raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive."))
72             elif not self.user_cache.is_active:
73                 raise forms.ValidationError(_("This account is inactive."))
74        
75         # TODO: determine whether this should move to its own method.
76         if self.request:
77             if not self.request.session.test_cookie_worked():
78                 raise forms.ValidationError(_("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in."))
79        
80         return self.cleaned_data
81    
82     def get_user_id(self):
83         if self.user_cache:
84             return self.user_cache.id
85         return None
86    
87     def get_user(self):
88         return self.user_cache
89
90 class PasswordResetForm(forms.Form):
91     email = forms.EmailField(label=_("E-mail"), max_length=40)
92    
93     def clean_email(self):
94         """
95         Validates that a user exists with the given e-mail address.
96         """
97         email = self.cleaned_data["email"]
98         self.users_cache = User.objects.filter(email__iexact=email)
99         if len(self.users_cache) == 0:
100             raise forms.ValidationError(_("That e-mail address doesn't have an associated user account. Are you sure you've registered?"))
101    
102     def save(self, domain_override=None, email_template_name='registration/password_reset_email.html'):
103         """
104         Calculates a new password randomly and sends it to the user.
105         """
106         from django.core.mail import send_mail
107         for user in self.users_cache:
108             new_pass = User.objects.make_random_password()
109             user.set_password(new_pass)
110             user.save()
111             if not domain_override:
112                 current_site = Site.objects.get_current()
113                 site_name = current_site.name
114                 domain = current_site.domain
115             else:
116                 site_name = domain = domain_override
117             t = loader.get_template(email_template_name)
118             c = {
119                 'new_password': new_pass,
120                 'email': user.email,
121                 'domain': domain,
122                 'site_name': site_name,
123                 'user': user,
124             }
125             send_mail(_("Password reset on %s") % site_name,
126                 t.render(Context(c)), None, [user.email])
127
128 class PasswordChangeForm(forms.Form):
129     """
130     A form that lets a user change his/her password.
131     """
132     old_password = forms.CharField(label=_("Old password"), max_length=30, widget=forms.PasswordInput)
133     new_password1 = forms.CharField(label=_("New password"), max_length=30, widget=forms.PasswordInput)
134     new_password2 = forms.CharField(label=_("New password confirmation"), max_length=30, widget=forms.PasswordInput)
135    
136     def __init__(self, user, *args, **kwargs):
137         self.user = user
138         super(PasswordChangeForm, self).__init__(*args, **kwargs)
139    
140     def clean_old_password(self):
141         """
142         Validates that the old_password field is correct.
143         """
144         old_password = self.cleaned_data["old_password"]
145         if not self.user.check_password(old_password):
146             raise forms.ValidationError(_("Your old password was entered incorrectly. Please enter it again."))
147         return old_password
148    
149     def clean_new_password2(self):
150         password1 = self.cleaned_data.get('new_password1')
151         password2 = self.cleaned_data.get('new_password2')
152         if password1 and password2:
153             if password1 != password2:
154                 raise forms.ValidationError(_("The two password fields didn't match."))
155         return password2
156    
157     def save(self, commit=True):
158         self.user.set_password(self.cleaned_data['new_password1'])
159         if commit:
160             self.user.save()
161         return self.user
162
163 class AdminPasswordChangeForm(forms.Form):
164     """
165     A form used to change the password of a user in the admin interface.
166     """
167     password1 = forms.CharField(label=_("Password"), max_length=60, widget=forms.PasswordInput)
168     password2 = forms.CharField(label=_("Password (again)"), max_length=60, widget=forms.PasswordInput)
169    
170     def __init__(self, user, *args, **kwargs):
171         self.user = user
172         super(AdminPasswordChangeForm, self).__init__(*args, **kwargs)
173    
174     def clean_password2(self):
175         password1 = self.cleaned_data.get('password1')
176         password2 = self.cleaned_data.get('password2')
177         if password1 and password2:
178             if password1 != password2:
179                 raise forms.ValidationError(_("The two password fields didn't match."))
180         return password2
181    
182     def save(self, commit=True):
183         """
184         Saves the new password.
185         """
186         self.user.set_password(self.cleaned_data["password1"])
187         if commit:
188             self.user.save()
189         return self.user
Note: See TracBrowser for help on using the browser.