Skip to content

Commit ba2d0fe

Browse files
committed
newforms-admin: Fixed #6083 -- Updated django.contrib.auth to use newforms. A big thanks to Greg Turner, Michael Newman and Petr Marhoun.
git-svn-id: http://code.djangoproject.com/svn/django/branches/newforms-admin@7191 bcc190cf-cafb-0310-a4f2-bffc1f526a37
1 parent 61b9c8f commit ba2d0fe

File tree

10 files changed

+417
-161
lines changed

10 files changed

+417
-161
lines changed

django/contrib/admin/templates/admin/auth/user/add_form.html

+7-4
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,21 @@
88
<fieldset class="module aligned">
99

1010
<div class="form-row">
11-
{{ form.username.html_error_list }}
11+
{{ form.username.errors }}
12+
{# TODO: get required class on label_tag #}
1213
<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>
1415
</div>
1516

1617
<div class="form-row">
17-
{{ form.password1.html_error_list }}
18+
{{ form.password1.errors }}
19+
{# TODO: get required class on label_tag #}
1820
<label for="id_password1" class="required">{% trans 'Password' %}:</label> {{ form.password1 }}
1921
</div>
2022

2123
<div class="form-row">
22-
{{ form.password2.html_error_list }}
24+
{{ form.password2.errors }}
25+
{# TODO: get required class on label_tag #}
2326
<label for="id_password2" class="required">{% trans 'Password (again)' %}:</label> {{ form.password2 }}
2427
<p class="help">{% trans 'Enter the same password as above, for verification.' %}</p>
2528
</div>

django/contrib/admin/templates/admin/auth/user/change_password.html

+6-4
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@
1818
<form action="{{ form_url }}" method="post" id="{{ opts.module_name }}_form">{% block form_top %}{% endblock %}
1919
<div>
2020
{% if is_popup %}<input type="hidden" name="_popup" value="1" />{% endif %}
21-
{% if form.error_dict %}
21+
{% if form.errors %}
2222
<p class="errornote">
23-
{% blocktrans count form.error_dict.items|length as counter %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}
23+
{% blocktrans count form.errors.items|length as counter %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}
2424
</p>
2525
{% endif %}
2626

@@ -29,12 +29,14 @@
2929
<fieldset class="module aligned">
3030

3131
<div class="form-row">
32-
{{ form.password1.html_error_list }}
32+
{{ form.password1.errors }}
33+
{# TODO: get required class on label_tag #}
3334
<label for="id_password1" class="required">{% trans 'Password' %}:</label> {{ form.password1 }}
3435
</div>
3536

3637
<div class="form-row">
37-
{{ form.password2.html_error_list }}
38+
{{ form.password2.errors }}
39+
{# TODO: get required class on label_tag #}
3840
<label for="id_password2" class="required">{% trans 'Password (again)' %}:</label> {{ form.password2 }}
3941
<p class="help">{% trans 'Enter the same password as above, for verification.' %}</p>
4042
</div>

django/contrib/auth/admin.py

+4-7
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,10 @@ class UserAdmin(admin.ModelAdmin):
2727
def add_view(self, request):
2828
if not self.has_change_permission(request):
2929
raise PermissionDenied
30-
manipulator = UserCreationForm()
3130
if request.method == 'POST':
32-
new_data = request.POST.copy()
33-
errors = manipulator.get_validation_errors(new_data)
34-
if not errors:
35-
new_user = manipulator.save(new_data)
31+
form = UserCreationForm(request.POST)
32+
if form.is_valid():
33+
new_user = form.save()
3634
msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': 'user', 'obj': new_user}
3735
if "_addanother" in request.POST:
3836
request.user.message_set.create(message=msg)
@@ -41,8 +39,7 @@ def add_view(self, request):
4139
request.user.message_set.create(message=msg + ' ' + ugettext("You may edit it again below."))
4240
return HttpResponseRedirect('../%s/' % new_user.id)
4341
else:
44-
errors = new_data = {}
45-
form = oldforms.FormWrapper(manipulator, new_data, errors)
42+
form = UserCreationForm()
4643
return render_to_response('admin/auth/user/add_form.html', {
4744
'title': _('Add user'),
4845
'form': form,

django/contrib/auth/forms.py

+139-94
Original file line numberDiff line numberDiff line change
@@ -3,88 +3,106 @@
33
from django.contrib.sites.models import Site
44
from django.template import Context, loader
55
from django.core import validators
6-
from django import oldforms
6+
from django import newforms as forms
77
from django.utils.translation import ugettext as _
88

9-
class UserCreationForm(oldforms.Manipulator):
10-
"A form that creates a user, with no privileges, from the given username and password."
11-
def __init__(self):
12-
self.fields = (
13-
oldforms.TextField(field_name='username', length=30, max_length=30, is_required=True,
14-
validator_list=[validators.isAlphaNumeric, self.isValidUsername]),
15-
oldforms.PasswordField(field_name='password1', length=30, max_length=60, is_required=True),
16-
oldforms.PasswordField(field_name='password2', length=30, max_length=60, is_required=True,
17-
validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]),
18-
)
19-
20-
def isValidUsername(self, field_data, all_data):
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"]
2125
try:
22-
User.objects.get(username=field_data)
26+
User.objects.get(username=username)
2327
except User.DoesNotExist:
24-
return
25-
raise validators.ValidationError, _('A user with that username already exists.')
26-
27-
def save(self, new_data):
28-
"Creates the user."
29-
return User.objects.create_user(new_data['username'], '', new_data['password1'])
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
3044

31-
class AuthenticationForm(oldforms.Manipulator):
45+
class AuthenticationForm(forms.Form):
3246
"""
3347
Base class for authenticating users. Extend this to get a form that accepts
3448
username/password logins.
3549
"""
36-
def __init__(self, request=None):
50+
username = forms.CharField(max_length=30)
51+
password = forms.CharField(max_length=30, widget=forms.PasswordInput)
52+
53+
def __init__(self, request=None, *args, **kwargs):
3754
"""
38-
If request is passed in, the manipulator will validate that cookies are
55+
If request is passed in, the form will validate that cookies are
3956
enabled. Note that the request (a HttpRequest object) must have set a
4057
cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
41-
running this validator.
58+
running this validation.
4259
"""
4360
self.request = request
44-
self.fields = [
45-
oldforms.TextField(field_name="username", length=15, max_length=30, is_required=True,
46-
validator_list=[self.isValidUser, self.hasCookiesEnabled]),
47-
oldforms.PasswordField(field_name="password", length=15, max_length=30, is_required=True),
48-
]
4961
self.user_cache = None
50-
51-
def hasCookiesEnabled(self, field_data, all_data):
52-
if self.request and not self.request.session.test_cookie_worked():
53-
raise validators.ValidationError, _("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in.")
54-
55-
def isValidUser(self, field_data, all_data):
56-
username = field_data
57-
password = all_data.get('password', None)
58-
self.user_cache = authenticate(username=username, password=password)
59-
if self.user_cache is None:
60-
raise validators.ValidationError, _("Please enter a correct username and password. Note that both fields are case-sensitive.")
61-
elif not self.user_cache.is_active:
62-
raise validators.ValidationError, _("This account is inactive.")
63-
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+
6482
def get_user_id(self):
6583
if self.user_cache:
6684
return self.user_cache.id
6785
return None
68-
86+
6987
def get_user(self):
7088
return self.user_cache
7189

72-
class PasswordResetForm(oldforms.Manipulator):
73-
"A form that lets a user request a password reset"
74-
def __init__(self):
75-
self.fields = (
76-
oldforms.EmailField(field_name="email", length=40, is_required=True,
77-
validator_list=[self.isValidUserEmail]),
78-
)
79-
80-
def isValidUserEmail(self, new_data, all_data):
81-
"Validates that a user exists with the given e-mail address"
82-
self.users_cache = list(User.objects.filter(email__iexact=new_data))
90+
class PasswordResetForm(forms.Form):
91+
email = forms.EmailField(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)
8399
if len(self.users_cache) == 0:
84-
raise validators.ValidationError, _("That e-mail address doesn't have an associated user account. Are you sure you've registered?")
85-
100+
raise forms.ValidationError(_("That e-mail address doesn't have an associated user account. Are you sure you've registered?"))
101+
86102
def save(self, domain_override=None, email_template_name='registration/password_reset_email.html'):
87-
"Calculates a new password randomly and sends it to the user"
103+
"""
104+
Calculates a new password randomly and sends it to the user.
105+
"""
88106
from django.core.mail import send_mail
89107
for user in self.users_cache:
90108
new_pass = User.objects.make_random_password()
@@ -103,42 +121,69 @@ def save(self, domain_override=None, email_template_name='registration/password_
103121
'domain': domain,
104122
'site_name': site_name,
105123
'user': user,
106-
}
107-
send_mail(_('Password reset on %s') % site_name, t.render(Context(c)), None, [user.email])
124+
}
125+
send_mail(_("Password reset on %s") % site_name,
126+
t.render(Context(c)), None, [user.email])
108127

109-
class PasswordChangeForm(oldforms.Manipulator):
110-
"A form that lets a user change his password."
111-
def __init__(self, user):
128+
class PasswordChangeForm(forms.Form):
129+
"""
130+
A form that lets a user change his/her password.
131+
"""
132+
old_password = forms.CharField(max_length=30, widget=forms.PasswordInput)
133+
new_password1 = forms.CharField(max_length=30, widget=forms.PasswordInput)
134+
new_password2 = forms.CharField(max_length=30, widget=forms.PasswordInput)
135+
136+
def __init__(self, user, *args, **kwargs):
112137
self.user = user
113-
self.fields = (
114-
oldforms.PasswordField(field_name="old_password", length=30, max_length=30, is_required=True,
115-
validator_list=[self.isValidOldPassword]),
116-
oldforms.PasswordField(field_name="new_password1", length=30, max_length=30, is_required=True,
117-
validator_list=[validators.AlwaysMatchesOtherField('new_password2', _("The two 'new password' fields didn't match."))]),
118-
oldforms.PasswordField(field_name="new_password2", length=30, max_length=30, is_required=True),
119-
)
120-
121-
def isValidOldPassword(self, new_data, all_data):
122-
"Validates that the old_password field is correct."
123-
if not self.user.check_password(new_data):
124-
raise validators.ValidationError, _("Your old password was entered incorrectly. Please enter it again.")
125-
126-
def save(self, new_data):
127-
"Saves the new password."
128-
self.user.set_password(new_data['new_password1'])
129-
self.user.save()
130-
131-
class AdminPasswordChangeForm(oldforms.Manipulator):
132-
"A form used to change the password of a user in the admin interface."
133-
def __init__(self, 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(max_length=60, widget=forms.PasswordInput)
168+
password2 = forms.CharField(max_length=60, widget=forms.PasswordInput)
169+
170+
def __init__(self, user, *args, **kwargs):
134171
self.user = user
135-
self.fields = (
136-
oldforms.PasswordField(field_name='password1', length=30, max_length=60, is_required=True),
137-
oldforms.PasswordField(field_name='password2', length=30, max_length=60, is_required=True,
138-
validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]),
139-
)
140-
141-
def save(self, new_data):
142-
"Saves the new password."
143-
self.user.set_password(new_data['password1'])
144-
self.user.save()
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

django/contrib/auth/tests/__init__.py

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from django.contrib.auth.tests.basic import BASIC_TESTS
2+
from django.contrib.auth.tests.forms import FORM_TESTS, PasswordResetFormTestCase
3+
4+
__test__ = {
5+
'BASIC_TESTS': BASIC_TESTS,
6+
'PASSWORDRESET_TESTS': PasswordResetFormTestCase,
7+
'FORM_TESTS': FORM_TESTS,
8+
}

django/contrib/auth/tests.py renamed to django/contrib/auth/tests/basic.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
"""
2-
>>> from models import User, AnonymousUser
1+
2+
BASIC_TESTS = """
3+
>>> from django.contrib.auth.models import User, AnonymousUser
34
>>> u = User.objects.create_user('testuser', '[email protected]', 'testpw')
45
>>> u.has_usable_password()
56
True

0 commit comments

Comments
 (0)