Code

Ticket #6083: 6083_newforms_auth2.diff

File 6083_newforms_auth2.diff, 33.5 KB (added by brosner, 6 years ago)

more complete with tests and docs. looking for feedback.

Line 
1diff --git a/django/contrib/admin/templates/admin/auth/user/add_form.html b/django/contrib/admin/templates/admin/auth/user/add_form.html
2index d478ec7..65824a6 100644
3--- a/django/contrib/admin/templates/admin/auth/user/add_form.html
4+++ b/django/contrib/admin/templates/admin/auth/user/add_form.html
5@@ -8,18 +8,21 @@
6 <fieldset class="module aligned">
7 
8 <div class="form-row">
9-  {{ form.username.html_error_list }}
10+  {{ form.username.errors }}
11+  {# TODO: get required class on label_tag #}
12   <label for="id_username" class="required">{% trans 'Username' %}:</label> {{ form.username }}
13-  <p class="help">{{ username_help_text }}</p>
14+  <p class="help">{{ form.username.help_text }}</p>
15 </div>
16 
17 <div class="form-row">
18-  {{ form.password1.html_error_list }}
19+  {{ form.password1.errors }}
20+  {# TODO: get required class on label_tag #}
21   <label for="id_password1" class="required">{% trans 'Password' %}:</label> {{ form.password1 }}
22 </div>
23 
24 <div class="form-row">
25-  {{ form.password2.html_error_list }}
26+  {{ form.password2.errors }}
27+  {# TODO: get required class on label_tag #}
28   <label for="id_password2" class="required">{% trans 'Password (again)' %}:</label> {{ form.password2 }}
29   <p class="help">{% trans 'Enter the same password as above, for verification.' %}</p>
30 </div>
31diff --git a/django/contrib/admin/templates/admin/auth/user/change_password.html b/django/contrib/admin/templates/admin/auth/user/change_password.html
32index a75ad87..5740feb 100644
33--- a/django/contrib/admin/templates/admin/auth/user/change_password.html
34+++ b/django/contrib/admin/templates/admin/auth/user/change_password.html
35@@ -18,9 +18,9 @@
36 <form action="{{ form_url }}" method="post" id="{{ opts.module_name }}_form">{% block form_top %}{% endblock %}
37 <div>
38 {% if is_popup %}<input type="hidden" name="_popup" value="1" />{% endif %}
39-{% if form.error_dict %}
40+{% if form.errors %}
41     <p class="errornote">
42-    {% blocktrans count form.error_dict.items|length as counter %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}
43+    {% blocktrans count form.errors.items|length as counter %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}
44     </p>
45 {% endif %}
46 
47@@ -29,12 +29,14 @@
48 <fieldset class="module aligned">
49 
50 <div class="form-row">
51-  {{ form.password1.html_error_list }}
52+  {{ form.password1.errors }}
53+  {# TODO: get required class on label_tag #}
54   <label for="id_password1" class="required">{% trans 'Password' %}:</label> {{ form.password1 }}
55 </div>
56 
57 <div class="form-row">
58-  {{ form.password2.html_error_list }}
59+  {{ form.password2.errors }}
60+  {# TODO: get required class on label_tag #}
61   <label for="id_password2" class="required">{% trans 'Password (again)' %}:</label> {{ form.password2 }}
62   <p class="help">{% trans 'Enter the same password as above, for verification.' %}</p>
63 </div>
64diff --git a/django/contrib/auth/admin.py b/django/contrib/auth/admin.py
65index 97d284c..3900e05 100644
66--- a/django/contrib/auth/admin.py
67+++ b/django/contrib/auth/admin.py
68@@ -27,12 +27,10 @@ class UserAdmin(admin.ModelAdmin):
69     def add_view(self, request):
70         if not self.has_change_permission(request):
71             raise PermissionDenied
72-        manipulator = UserCreationForm()
73         if request.method == 'POST':
74-            new_data = request.POST.copy()
75-            errors = manipulator.get_validation_errors(new_data)
76-            if not errors:
77-                new_user = manipulator.save(new_data)
78+            form = UserCreationForm(request.POST)
79+            if form.is_valid():
80+                new_user = form.save()
81                 msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': 'user', 'obj': new_user}
82                 if "_addanother" in request.POST:
83                     request.user.message_set.create(message=msg)
84@@ -41,8 +39,7 @@ class UserAdmin(admin.ModelAdmin):
85                     request.user.message_set.create(message=msg + ' ' + ugettext("You may edit it again below."))
86                     return HttpResponseRedirect('../%s/' % new_user.id)
87         else:
88-            errors = new_data = {}
89-        form = oldforms.FormWrapper(manipulator, new_data, errors)
90+            form = UserCreationForm()
91         return render_to_response('admin/auth/user/add_form.html', {
92             'title': _('Add user'),
93             'form': form,
94diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py
95index 47a974c..a1066aa 100644
96--- a/django/contrib/auth/forms.py
97+++ b/django/contrib/auth/forms.py
98@@ -3,88 +3,107 @@ from django.contrib.auth import authenticate
99 from django.contrib.sites.models import Site
100 from django.template import Context, loader
101 from django.core import validators
102-from django import oldforms
103+from django import newforms as forms
104 from django.utils.translation import ugettext as _
105 
106-class UserCreationForm(oldforms.Manipulator):
107-    "A form that creates a user, with no privileges, from the given username and password."
108-    def __init__(self):
109-        self.fields = (
110-            oldforms.TextField(field_name='username', length=30, max_length=30, is_required=True,
111-                validator_list=[validators.isAlphaNumeric, self.isValidUsername]),
112-            oldforms.PasswordField(field_name='password1', length=30, max_length=60, is_required=True),
113-            oldforms.PasswordField(field_name='password2', length=30, max_length=60, is_required=True,
114-                validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]),
115-        )
116-
117-    def isValidUsername(self, field_data, all_data):
118+class UserCreationForm(forms.ModelForm):
119+    """
120+    A form that creates a user, with no privileges, from the given username and password.
121+    """
122+    username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^\w+$',
123+        help_text = _("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)."),
124+        error_message = _("This value must contain only letters, numbers and underscores."))
125+    password1 = forms.CharField(label=_("Password"), max_length=60, widget=forms.PasswordInput)
126+    password2 = forms.CharField(label=_("Password confirmation"), max_length=60, widget=forms.PasswordInput)
127+   
128+    class Meta:
129+        model = User
130+        fields = ("username",)
131+   
132+    def clean_username(self):
133+        username = self.cleaned_data["username"]
134         try:
135-            User.objects.get(username=field_data)
136+            User.objects.get(username=username)
137         except User.DoesNotExist:
138-            return
139-        raise validators.ValidationError, _('A user with that username already exists.')
140-
141-    def save(self, new_data):
142-        "Creates the user."
143-        return User.objects.create_user(new_data['username'], '', new_data['password1'])
144+            return username
145+        raise forms.ValidationError(_("A user with that username already exists."))
146+   
147+    def clean_password2(self):
148+        password1 = self.cleaned_data["password1"]
149+        password2 = self.cleaned_data["password2"]
150+        if password1 != password2:
151+            raise forms.ValidationError(_("The two password fields didn't match."))
152+        return password2
153+   
154+    def save(self, commit=True):
155+        user = super(UserCreationForm, self).save(commit=False)
156+        user.set_password(self.cleaned_data["password1"])
157+        if commit:
158+            user.save()
159+        return user
160 
161-class AuthenticationForm(oldforms.Manipulator):
162+class AuthenticationForm(forms.Form):
163     """
164     Base class for authenticating users. Extend this to get a form that accepts
165     username/password logins.
166     """
167-    def __init__(self, request=None):
168+    username = forms.CharField(max_length=30)
169+    password = forms.CharField(max_length=30, widget=forms.PasswordInput)
170+   
171+    def __init__(self, request=None, *args, **kwargs):
172         """
173-        If request is passed in, the manipulator will validate that cookies are
174+        If request is passed in, the form will validate that cookies are
175         enabled. Note that the request (a HttpRequest object) must have set a
176         cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
177-        running this validator.
178+        running this validation.
179         """
180         self.request = request
181-        self.fields = [
182-            oldforms.TextField(field_name="username", length=15, max_length=30, is_required=True,
183-                validator_list=[self.isValidUser, self.hasCookiesEnabled]),
184-            oldforms.PasswordField(field_name="password", length=15, max_length=30, is_required=True),
185-        ]
186         self.user_cache = None
187-
188-    def hasCookiesEnabled(self, field_data, all_data):
189-        if self.request and not self.request.session.test_cookie_worked():
190-            raise validators.ValidationError, _("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in.")
191-
192-    def isValidUser(self, field_data, all_data):
193-        username = field_data
194-        password = all_data.get('password', None)
195-        self.user_cache = authenticate(username=username, password=password)
196-        if self.user_cache is None:
197-            raise validators.ValidationError, _("Please enter a correct username and password. Note that both fields are case-sensitive.")
198-        elif not self.user_cache.is_active:
199-            raise validators.ValidationError, _("This account is inactive.")
200-
201+        super(AuthenticationForm, self).__init__(*args, **kwargs)
202+   
203+    def clean(self):
204+        username = self.cleaned_data.get('username')
205+        password = self.cleaned_data.get('password')
206+       
207+        if username and password:
208+            self.user_cache = authenticate(username=username, password=password)
209+            if self.user_cache is None:
210+                raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive."))
211+            elif not self.user_cache.is_active:
212+                raise forms.ValidationError(_("This account is inactive."))
213+       
214+        # TODO: determine whether this should move to its own method.
215+        if self.request:
216+            if not self.request.session.test_cookie_worked():
217+                raise forms.ValidationError(_("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in."))
218+       
219+        return self.cleaned_data
220+   
221     def get_user_id(self):
222         if self.user_cache:
223             return self.user_cache.id
224         return None
225-
226+   
227     def get_user(self):
228         return self.user_cache
229 
230-class PasswordResetForm(oldforms.Manipulator):
231-    "A form that lets a user request a password reset"
232-    def __init__(self):
233-        self.fields = (
234-            oldforms.EmailField(field_name="email", length=40, is_required=True,
235-                validator_list=[self.isValidUserEmail]),
236-        )
237-
238-    def isValidUserEmail(self, new_data, all_data):
239-        "Validates that a user exists with the given e-mail address"
240-        self.users_cache = list(User.objects.filter(email__iexact=new_data))
241+class PasswordResetForm(forms.Form):
242+    # used to be length of 40
243+    email = forms.EmailField()
244+   
245+    def clean_email(self):
246+        """
247+        Validates that a user exists with the given e-mail address.
248+        """
249+        email = self.cleaned_data["email"]
250+        self.users_cache = User.objects.filter(email__iexact=email)
251         if len(self.users_cache) == 0:
252-            raise validators.ValidationError, _("That e-mail address doesn't have an associated user account. Are you sure you've registered?")
253-
254+            raise forms.ValidationError(_("That e-mail address doesn't have an associated user account. Are you sure you've registered?"))
255+   
256     def save(self, domain_override=None, email_template_name='registration/password_reset_email.html'):
257-        "Calculates a new password randomly and sends it to the user"
258+        """
259+        Calculates a new password randomly and sends it to the user.
260+        """
261         from django.core.mail import send_mail
262         for user in self.users_cache:
263             new_pass = User.objects.make_random_password()
264@@ -103,42 +122,69 @@ class PasswordResetForm(oldforms.Manipulator):
265                 'domain': domain,
266                 'site_name': site_name,
267                 'user': user,
268-                }
269-            send_mail(_('Password reset on %s') % site_name, t.render(Context(c)), None, [user.email])
270+            }
271+            send_mail(_("Password reset on %s") % site_name,
272+                t.render(Context(c)), None, [user.email])
273 
274-class PasswordChangeForm(oldforms.Manipulator):
275-    "A form that lets a user change his password."
276-    def __init__(self, user):
277+class PasswordChangeForm(forms.Form):
278+    """
279+    A form that lets a user change his/her password.
280+    """
281+    old_password = forms.CharField(max_length=30, widget=forms.PasswordInput)
282+    new_password1 = forms.CharField(max_length=30, widget=forms.PasswordInput)
283+    new_password2 = forms.CharField(max_length=30, widget=forms.PasswordInput)
284+   
285+    def __init__(self, user, *args, **kwargs):
286         self.user = user
287-        self.fields = (
288-            oldforms.PasswordField(field_name="old_password", length=30, max_length=30, is_required=True,
289-                validator_list=[self.isValidOldPassword]),
290-            oldforms.PasswordField(field_name="new_password1", length=30, max_length=30, is_required=True,
291-                validator_list=[validators.AlwaysMatchesOtherField('new_password2', _("The two 'new password' fields didn't match."))]),
292-            oldforms.PasswordField(field_name="new_password2", length=30, max_length=30, is_required=True),
293-        )
294-
295-    def isValidOldPassword(self, new_data, all_data):
296-        "Validates that the old_password field is correct."
297-        if not self.user.check_password(new_data):
298-            raise validators.ValidationError, _("Your old password was entered incorrectly. Please enter it again.")
299-
300-    def save(self, new_data):
301-        "Saves the new password."
302-        self.user.set_password(new_data['new_password1'])
303-        self.user.save()
304-
305-class AdminPasswordChangeForm(oldforms.Manipulator):
306-    "A form used to change the password of a user in the admin interface."
307-    def __init__(self, user):
308+        super(PasswordChangeForm, self).__init__(*args, **kwargs)
309+   
310+    def clean_old_password(self):
311+        """
312+        Validates that the old_password field is correct.
313+        """
314+        old_password = self.cleaned_data["old_password"]
315+        if not self.user.check_password(old_password):
316+            raise forms.ValidationError(_("Your old password was entered incorrectly. Please enter it again."))
317+        return old_password
318+   
319+    def clean_new_password2(self):
320+        password1 = self.cleaned_data.get('new_password1')
321+        password2 = self.cleaned_data.get('new_password2')
322+        if password1 and password2:
323+            if password1 != password2:
324+                raise forms.ValidationError(_("The two password fields didn't match."))
325+        return password2
326+   
327+    def save(self, commit=True):
328+        self.user.set_password(self.cleaned_data['new_password1'])
329+        if commit:
330+            self.user.save()
331+        return self.user
332+
333+class AdminPasswordChangeForm(forms.Form):
334+    """
335+    A form used to change the password of a user in the admin interface.
336+    """
337+    password1 = forms.CharField(max_length=60, widget=forms.PasswordInput)
338+    password2 = forms.CharField(max_length=60, widget=forms.PasswordInput)
339+   
340+    def __init__(self, user, *args, **kwargs):
341         self.user = user
342-        self.fields = (
343-            oldforms.PasswordField(field_name='password1', length=30, max_length=60, is_required=True),
344-            oldforms.PasswordField(field_name='password2', length=30, max_length=60, is_required=True,
345-                validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]),
346-        )
347-
348-    def save(self, new_data):
349-        "Saves the new password."
350-        self.user.set_password(new_data['password1'])
351-        self.user.save()
352+        super(AdminPasswordChangeForm, self).__init__(*args, **kwargs)
353+   
354+    def clean_password2(self):
355+        password1 = self.cleaned_data.get('password1')
356+        password2 = self.cleaned_data.get('password2')
357+        if password1 and password2:
358+            if password1 != password2:
359+                raise forms.ValidationError(_("The two password fields didn't match."))
360+        return password2
361+   
362+    def save(self, commit=True):
363+        """
364+        Saves the new password.
365+        """
366+        self.user.set_password(self.cleaned_data["password1"])
367+        if commit:
368+            self.user.save()
369+        return self.user
370diff --git a/django/contrib/auth/tests.py b/django/contrib/auth/tests.py
371deleted file mode 100644
372index d369ac5..0000000
373--- a/django/contrib/auth/tests.py
374+++ /dev/null
375@@ -1,38 +0,0 @@
376-"""
377->>> from models import User, AnonymousUser
378->>> u = User.objects.create_user('testuser', 'test@example.com', 'testpw')
379->>> u.has_usable_password()
380-True
381->>> u.check_password('bad')
382-False
383->>> u.check_password('testpw')
384-True
385->>> u.set_unusable_password()
386->>> u.save()
387->>> u.check_password('testpw')
388-False
389->>> u.has_usable_password()
390-False
391->>> u2 = User.objects.create_user('testuser2', 'test2@example.com')
392->>> u2.has_usable_password()
393-False
394-
395->>> u.is_authenticated()
396-True
397->>> u.is_staff
398-False
399->>> u.is_active
400-True
401-
402->>> a = AnonymousUser()
403->>> a.is_authenticated()
404-False
405->>> a.is_staff
406-False
407->>> a.is_active
408-False
409->>> a.groups.all()
410-[]
411->>> a.user_permissions.all()
412-[]
413-"""
414\ No newline at end of file
415diff --git a/django/contrib/auth/tests/__init__.py b/django/contrib/auth/tests/__init__.py
416new file mode 100644
417index 0000000..092fdd5
418--- /dev/null
419+++ b/django/contrib/auth/tests/__init__.py
420@@ -0,0 +1,8 @@
421+from django.contrib.auth.tests.basic import BASIC_TESTS
422+from django.contrib.auth.tests.forms import FORM_TESTS, PasswordResetFormTestCase
423+
424+__test__ = {
425+    'BASIC_TESTS': BASIC_TESTS,
426+    'PASSWORDRESET_TESTS': PasswordResetFormTestCase,
427+    'FORM_TESTS': FORM_TESTS,
428+}
429diff --git a/django/contrib/auth/tests/basic.py b/django/contrib/auth/tests/basic.py
430new file mode 100644
431index 0000000..950815e
432--- /dev/null
433+++ b/django/contrib/auth/tests/basic.py
434@@ -0,0 +1,39 @@
435+
436+BASIC_TESTS = """
437+>>> from django.contrib.auth.models import User, AnonymousUser
438+>>> u = User.objects.create_user('testuser', 'test@example.com', 'testpw')
439+>>> u.has_usable_password()
440+True
441+>>> u.check_password('bad')
442+False
443+>>> u.check_password('testpw')
444+True
445+>>> u.set_unusable_password()
446+>>> u.save()
447+>>> u.check_password('testpw')
448+False
449+>>> u.has_usable_password()
450+False
451+>>> u2 = User.objects.create_user('testuser2', 'test2@example.com')
452+>>> u2.has_usable_password()
453+False
454+
455+>>> u.is_authenticated()
456+True
457+>>> u.is_staff
458+False
459+>>> u.is_active
460+True
461+
462+>>> a = AnonymousUser()
463+>>> a.is_authenticated()
464+False
465+>>> a.is_staff
466+False
467+>>> a.is_active
468+False
469+>>> a.groups.all()
470+[]
471+>>> a.user_permissions.all()
472+[]
473+"""
474\ No newline at end of file
475diff --git a/django/contrib/auth/tests/forms.py b/django/contrib/auth/tests/forms.py
476new file mode 100644
477index 0000000..001323b
478--- /dev/null
479+++ b/django/contrib/auth/tests/forms.py
480@@ -0,0 +1,164 @@
481+
482+from django.core import mail
483+from django.test import TestCase
484+from django.contrib.auth.models import User
485+from django.contrib.auth.forms import PasswordResetForm
486+
487+class PasswordResetFormTestCase(TestCase):
488+    def testValidUser(self):
489+        data = {
490+            'email': 'nonexistent@example.com',
491+        }
492+        form = PasswordResetForm(data)
493+        self.assertEqual(form.is_valid(), False)
494+        self.assertEqual(form["email"].errors, [u"That e-mail address doesn't have an associated user account. Are you sure you've registered?"])
495+   
496+    def testEmail(self):
497+        # TODO: remove my email address from the test ;)
498+        User.objects.create_user('atestuser', 'atestuser@example.com', 'test789')
499+        data = {
500+            'email': 'atestuser@example.com',
501+        }
502+        form = PasswordResetForm(data)
503+        self.assertEqual(form.is_valid(), True)
504+        # TODO: look at why using contrib.sites breaks other tests
505+        form.save(domain_override="example.com")
506+        self.assertEqual(len(mail.outbox), 1)
507+        self.assertEqual(mail.outbox[0].subject, u'Password reset on example.com')
508+        # TODO: test mail body. need to figure out a way to get the password in plain text
509+        # self.assertEqual(mail.outbox[0].body, '')
510+
511+FORM_TESTS = """
512+>>> from django.contrib.auth.models import User
513+>>> from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
514+>>> from django.contrib.auth.forms import PasswordChangeForm
515+
516+The user already exists.
517+
518+>>> user = User.objects.create_user("jsmith", "jsmith@example.com", "test123")
519+>>> data = {
520+...     'username': 'jsmith',
521+...     'password1': 'test123',
522+...     'password2': 'test123',
523+... }
524+>>> form = UserCreationForm(data)
525+>>> form.is_valid()
526+False
527+>>> form["username"].errors
528+[u'A user with that username already exists.']
529+
530+The username contains invalid data.
531+
532+>>> data = {
533+...     'username': 'jsmith@example.com',
534+...     'password1': 'test123',
535+...     'password2': 'test123',
536+... }
537+>>> form = UserCreationForm(data)
538+>>> form.is_valid()
539+False
540+>>> form["username"].errors
541+[u'This value must contain only letters, numbers and underscores.']
542+
543+The verification password is incorrect.
544+
545+>>> data = {
546+...     'username': 'jsmith2',
547+...     'password1': 'test123',
548+...     'password2': 'test',
549+... }
550+>>> form = UserCreationForm(data)
551+>>> form.is_valid()
552+False
553+>>> form["password2"].errors
554+[u"The two password fields didn't match."]
555+
556+The success case.
557+
558+>>> data = {
559+...     'username': 'jsmith2',
560+...     'password1': 'test123',
561+...     'password2': 'test123',
562+... }
563+>>> form = UserCreationForm(data)
564+>>> form.is_valid()
565+True
566+>>> form.save()
567+<User: jsmith2>
568+
569+The user submits an invalid username.
570+
571+>>> data = {
572+...     'username': 'jsmith_does_not_exist',
573+...     'password': 'test123',
574+... }
575+
576+>>> form = AuthenticationForm(None, data)
577+>>> form.is_valid()
578+False
579+>>> form.non_field_errors()
580+[u'Please enter a correct username and password. Note that both fields are case-sensitive.']
581+
582+The user is inactive.
583+
584+>>> data = {
585+...     'username': 'jsmith',
586+...     'password': 'test123',
587+... }
588+>>> user.is_active = False
589+>>> user.save()
590+>>> form = AuthenticationForm(None, data)
591+>>> form.is_valid()
592+False
593+>>> form.non_field_errors()
594+[u'This account is inactive.']
595+
596+>>> user.is_active = True
597+>>> user.save()
598+
599+The success case
600+
601+>>> form = AuthenticationForm(None, data)
602+>>> form.is_valid()
603+True
604+>>> form.non_field_errors()
605+[]
606+
607+The old password is incorrect.
608+
609+>>> data = {
610+...     'old_password': 'test',
611+...     'new_password1': 'abc123',
612+...     'new_password2': 'abc123',
613+... }
614+>>> form = PasswordChangeForm(user, data)
615+>>> form.is_valid()
616+False
617+>>> form["old_password"].errors
618+[u'Your old password was entered incorrectly. Please enter it again.']
619+
620+The two new passwords do not match.
621+
622+>>> data = {
623+...     'old_password': 'test123',
624+...     'new_password1': 'abc123',
625+...     'new_password2': 'abc',
626+... }
627+>>> form = PasswordChangeForm(user, data)
628+>>> form.is_valid()
629+False
630+>>> form["new_password2"].errors
631+[u"The two password fields didn't match."]
632+
633+The success case.
634+
635+>>> data = {
636+...     'old_password': 'test123',
637+...     'new_password1': 'abc123',
638+...     'new_password2': 'abc123',
639+... }
640+>>> form = PasswordChangeForm(user, data)
641+>>> form.is_valid()
642+True
643+
644+"""
645diff --git a/django/contrib/auth/views.py b/django/contrib/auth/views.py
646index 509b96e..65d6b29 100644
647--- a/django/contrib/auth/views.py
648+++ b/django/contrib/auth/views.py
649@@ -1,7 +1,6 @@
650 from django.contrib.auth.forms import AuthenticationForm
651 from django.contrib.auth.forms import PasswordResetForm, PasswordChangeForm, AdminPasswordChangeForm
652 from django.core.exceptions import PermissionDenied
653-from django import oldforms
654 from django.shortcuts import render_to_response, get_object_or_404
655 from django.template import RequestContext
656 from django.contrib.sites.models import Site, RequestSite
657@@ -14,30 +13,27 @@ from django.contrib.auth.models import User
658 
659 def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME):
660     "Displays the login form and handles the login action."
661-    manipulator = AuthenticationForm(request)
662     redirect_to = request.REQUEST.get(redirect_field_name, '')
663-    if request.POST:
664-        errors = manipulator.get_validation_errors(request.POST)
665-        if not errors:
666+    if request.method == "POST":
667+        form = AuthenticationForm(request, request.POST)
668+        if form.is_valid():
669             # Light security check -- make sure redirect_to isn't garbage.
670             if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
671                 from django.conf import settings
672                 redirect_to = settings.LOGIN_REDIRECT_URL
673             from django.contrib.auth import login
674-            login(request, manipulator.get_user())
675+            login(request, form.get_user())
676             request.session.delete_test_cookie()
677             return HttpResponseRedirect(redirect_to)
678     else:
679-        errors = {}
680+        form = AuthenticationForm(request)
681     request.session.set_test_cookie()
682-
683     if Site._meta.installed:
684         current_site = Site.objects.get_current()
685     else:
686         current_site = RequestSite(request)
687-
688     return render_to_response(template_name, {
689-        'form': oldforms.FormWrapper(manipulator, request.POST, errors),
690+        'form': form,
691         redirect_field_name: redirect_to,
692         'site_name': current_site.name,
693     }, context_instance=RequestContext(request))
694@@ -68,55 +64,54 @@ def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_N
695 
696 def password_reset(request, is_admin_site=False, template_name='registration/password_reset_form.html',
697         email_template_name='registration/password_reset_email.html'):
698-    new_data, errors = {}, {}
699-    form = PasswordResetForm()
700-    if request.POST:
701-        new_data = request.POST.copy()
702-        errors = form.get_validation_errors(new_data)
703-        if not errors:
704+    if request.method == "POST":
705+        form = PasswordResetForm(request.POST)
706+        if form.is_valid():
707             if is_admin_site:
708                 form.save(domain_override=request.META['HTTP_HOST'])
709             else:
710                 form.save(email_template_name=email_template_name)
711             return HttpResponseRedirect('%sdone/' % request.path)
712-    return render_to_response(template_name, {'form': oldforms.FormWrapper(form, new_data, errors)},
713-        context_instance=RequestContext(request))
714+    else:
715+        form = PasswordResetForm()
716+    return render_to_response(template_name, {
717+        'form': form,
718+    }, context_instance=RequestContext(request))
719 
720 def password_reset_done(request, template_name='registration/password_reset_done.html'):
721     return render_to_response(template_name, context_instance=RequestContext(request))
722 
723 def password_change(request, template_name='registration/password_change_form.html'):
724-    new_data, errors = {}, {}
725-    form = PasswordChangeForm(request.user)
726-    if request.POST:
727-        new_data = request.POST.copy()
728-        errors = form.get_validation_errors(new_data)
729-        if not errors:
730-            form.save(new_data)
731+    if request.method == "POST":
732+        form = PasswordChangeForm(request.user, request.POST)
733+        if form.is_valid():
734+            form.save()
735             return HttpResponseRedirect('%sdone/' % request.path)
736-    return render_to_response(template_name, {'form': oldforms.FormWrapper(form, new_data, errors)},
737-        context_instance=RequestContext(request))
738+    else:
739+        form = PasswordChangeForm(request.user)
740+    return render_to_response(template_name, {
741+        'form': form,
742+    }, context_instance=RequestContext(request))
743 password_change = login_required(password_change)
744 
745 def password_change_done(request, template_name='registration/password_change_done.html'):
746     return render_to_response(template_name, context_instance=RequestContext(request))
747 
748+# TODO: move to admin.py in the ModelAdmin
749 def user_change_password(request, id):
750+    from django import oldforms
751     if not request.user.has_perm('auth.change_user'):
752         raise PermissionDenied
753     user = get_object_or_404(User, pk=id)
754-    manipulator = AdminPasswordChangeForm(user)
755     if request.method == 'POST':
756-        new_data = request.POST.copy()
757-        errors = manipulator.get_validation_errors(new_data)
758-        if not errors:
759-            new_user = manipulator.save(new_data)
760+        form = AdminPasswordChangeForm(user, request.POST)
761+        if form.is_valid():
762+            new_user = form.save()
763             msg = _('Password changed successfully.')
764             request.user.message_set.create(message=msg)
765             return HttpResponseRedirect('..')
766     else:
767-        errors = new_data = {}
768-    form = oldforms.FormWrapper(manipulator, new_data, errors)
769+        form = AdminPasswordChangeForm(user)
770     return render_to_response('admin/auth/user/change_password.html', {
771         'title': _('Change password: %s') % escape(user.username),
772         'form': form,
773diff --git a/django/contrib/comments/views/comments.py b/django/contrib/comments/views/comments.py
774index 67da575..aac489f 100644
775--- a/django/contrib/comments/views/comments.py
776+++ b/django/contrib/comments/views/comments.py
777@@ -17,6 +17,47 @@ import base64, datetime
778 
779 COMMENTS_PER_PAGE = 20
780 
781+class AuthenticationForm(oldforms.Manipulator):
782+    """
783+    Base class for authenticating users. Extend this to get a form that accepts
784+    username/password logins.
785+    """
786+    def __init__(self, request=None):
787+        """
788+        If request is passed in, the manipulator will validate that cookies are
789+        enabled. Note that the request (a HttpRequest object) must have set a
790+        cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
791+        running this validator.
792+        """
793+        self.request = request
794+        self.fields = [
795+            oldforms.TextField(field_name="username", length=15, max_length=30, is_required=True,
796+                validator_list=[self.isValidUser, self.hasCookiesEnabled]),
797+            oldforms.PasswordField(field_name="password", length=15, max_length=30, is_required=True),
798+        ]
799+        self.user_cache = None
800+
801+    def hasCookiesEnabled(self, field_data, all_data):
802+        if self.request and not self.request.session.test_cookie_worked():
803+            raise validators.ValidationError, _("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in.")
804+
805+    def isValidUser(self, field_data, all_data):
806+        username = field_data
807+        password = all_data.get('password', None)
808+        self.user_cache = authenticate(username=username, password=password)
809+        if self.user_cache is None:
810+            raise validators.ValidationError, _("Please enter a correct username and password. Note that both fields are case-sensitive.")
811+        elif not self.user_cache.is_active:
812+            raise validators.ValidationError, _("This account is inactive.")
813+
814+    def get_user_id(self):
815+        if self.user_cache:
816+            return self.user_cache.id
817+        return None
818+
819+    def get_user(self):
820+        return self.user_cache
821+
822 class PublicCommentManipulator(AuthenticationForm):
823     "Manipulator that handles public registered comments"
824     def __init__(self, user, ratings_required, ratings_range, num_rating_choices):
825diff --git a/docs/authentication.txt b/docs/authentication.txt
826index 5134e90..4d45fd9 100644
827--- a/docs/authentication.txt
828+++ b/docs/authentication.txt
829@@ -666,29 +666,29 @@ successful login.
830     * ``login_url``: The URL of the login page to redirect to. This
831       will default to ``settings.LOGIN_URL`` if not supplied.
832 
833-Built-in manipulators
834----------------------
835+Built-in forms
836+--------------
837+
838+**New in Django development version.**
839 
840 If you don't want to use the built-in views, but want the convenience
841-of not having to write manipulators for this functionality, the
842-authentication system provides several built-in manipulators:
843+of not having to write forms for this functionality, the authentication
844+system provides several built-in forms:
845 
846-    * ``django.contrib.auth.forms.AdminPasswordChangeForm``: A
847-      manipulator used in the admin interface to change a user's
848-      password.
849+    * ``django.contrib.auth.forms.AdminPasswordChangeForm``: A form used in
850+      the admin interface to change a user's password.
851 
852-    * ``django.contrib.auth.forms.AuthenticationForm``: A manipulator
853-      for logging a user in.
854+    * ``django.contrib.auth.forms.AuthenticationForm``: A form for logging a
855+      user in.
856 
857-    * ``django.contrib.auth.forms.PasswordChangeForm``: A manipulator
858-      for allowing a user to change their password.
859+    * ``django.contrib.auth.forms.PasswordChangeForm``: A form for allowing a
860+      user to change their password.
861 
862-    * ``django.contrib.auth.forms.PasswordResetForm``: A manipulator
863-      for resetting a user's password and emailing the new password to
864-      them.
865+    * ``django.contrib.auth.forms.PasswordResetForm``: A form for resetting a
866+      user's password and emailing the new password to them.
867 
868-    * ``django.contrib.auth.forms.UserCreationForm``: A manipulator
869-      for creating a new user.
870+    * ``django.contrib.auth.forms.UserCreationForm``: A form for creating a
871+      new user.
872 
873 Limiting access to logged-in users that pass a test
874 ---------------------------------------------------