Permalink
Browse files

newforms-admin: Fixed #6083 -- Updated django.contrib.auth to use new…

…forms. 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
  • Loading branch information...
1 parent 61b9c8f commit ba2d0feb72c5df4f72b92a3ccf39436f6fbdaee3 @brosner brosner committed Mar 3, 2008
@@ -8,18 +8,21 @@
<fieldset class="module aligned">
<div class="form-row">
- {{ form.username.html_error_list }}
+ {{ form.username.errors }}
+ {# TODO: get required class on label_tag #}
<label for="id_username" class="required">{% trans 'Username' %}:</label> {{ form.username }}
- <p class="help">{{ username_help_text }}</p>
+ <p class="help">{{ form.username.help_text }}</p>
</div>
<div class="form-row">
- {{ form.password1.html_error_list }}
+ {{ form.password1.errors }}
+ {# TODO: get required class on label_tag #}
<label for="id_password1" class="required">{% trans 'Password' %}:</label> {{ form.password1 }}
</div>
<div class="form-row">
- {{ form.password2.html_error_list }}
+ {{ form.password2.errors }}
+ {# TODO: get required class on label_tag #}
<label for="id_password2" class="required">{% trans 'Password (again)' %}:</label> {{ form.password2 }}
<p class="help">{% trans 'Enter the same password as above, for verification.' %}</p>
</div>
@@ -18,9 +18,9 @@
<form action="{{ form_url }}" method="post" id="{{ opts.module_name }}_form">{% block form_top %}{% endblock %}
<div>
{% if is_popup %}<input type="hidden" name="_popup" value="1" />{% endif %}
-{% if form.error_dict %}
+{% if form.errors %}
<p class="errornote">
- {% blocktrans count form.error_dict.items|length as counter %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}
+ {% blocktrans count form.errors.items|length as counter %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}
</p>
{% endif %}
@@ -29,12 +29,14 @@
<fieldset class="module aligned">
<div class="form-row">
- {{ form.password1.html_error_list }}
+ {{ form.password1.errors }}
+ {# TODO: get required class on label_tag #}
<label for="id_password1" class="required">{% trans 'Password' %}:</label> {{ form.password1 }}
</div>
<div class="form-row">
- {{ form.password2.html_error_list }}
+ {{ form.password2.errors }}
+ {# TODO: get required class on label_tag #}
<label for="id_password2" class="required">{% trans 'Password (again)' %}:</label> {{ form.password2 }}
<p class="help">{% trans 'Enter the same password as above, for verification.' %}</p>
</div>
@@ -27,12 +27,10 @@ class UserAdmin(admin.ModelAdmin):
def add_view(self, request):
if not self.has_change_permission(request):
raise PermissionDenied
- manipulator = UserCreationForm()
if request.method == 'POST':
- new_data = request.POST.copy()
- errors = manipulator.get_validation_errors(new_data)
- if not errors:
- new_user = manipulator.save(new_data)
+ form = UserCreationForm(request.POST)
+ if form.is_valid():
+ new_user = form.save()
msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': 'user', 'obj': new_user}
if "_addanother" in request.POST:
request.user.message_set.create(message=msg)
@@ -41,8 +39,7 @@ def add_view(self, request):
request.user.message_set.create(message=msg + ' ' + ugettext("You may edit it again below."))
return HttpResponseRedirect('../%s/' % new_user.id)
else:
- errors = new_data = {}
- form = oldforms.FormWrapper(manipulator, new_data, errors)
+ form = UserCreationForm()
return render_to_response('admin/auth/user/add_form.html', {
'title': _('Add user'),
'form': form,
@@ -3,88 +3,106 @@
from django.contrib.sites.models import Site
from django.template import Context, loader
from django.core import validators
-from django import oldforms
+from django import newforms as forms
from django.utils.translation import ugettext as _
-class UserCreationForm(oldforms.Manipulator):
- "A form that creates a user, with no privileges, from the given username and password."
- def __init__(self):
- self.fields = (
- oldforms.TextField(field_name='username', length=30, max_length=30, is_required=True,
- validator_list=[validators.isAlphaNumeric, self.isValidUsername]),
- oldforms.PasswordField(field_name='password1', length=30, max_length=60, is_required=True),
- oldforms.PasswordField(field_name='password2', length=30, max_length=60, is_required=True,
- validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]),
- )
-
- def isValidUsername(self, field_data, all_data):
+class UserCreationForm(forms.ModelForm):
+ """
+ A form that creates a user, with no privileges, from the given username and password.
+ """
+ username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^\w+$',
+ help_text = _("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)."),
+ error_message = _("This value must contain only letters, numbers and underscores."))
+ password1 = forms.CharField(label=_("Password"), max_length=60, widget=forms.PasswordInput)
+ password2 = forms.CharField(label=_("Password confirmation"), max_length=60, widget=forms.PasswordInput)
+
+ class Meta:
+ model = User
+ fields = ("username",)
+
+ def clean_username(self):
+ username = self.cleaned_data["username"]
try:
- User.objects.get(username=field_data)
+ User.objects.get(username=username)
except User.DoesNotExist:
- return
- raise validators.ValidationError, _('A user with that username already exists.')
-
- def save(self, new_data):
- "Creates the user."
- return User.objects.create_user(new_data['username'], '', new_data['password1'])
+ return username
+ raise forms.ValidationError(_("A user with that username already exists."))
+
+ def clean_password2(self):
+ password1 = self.cleaned_data["password1"]
+ password2 = self.cleaned_data["password2"]
+ if password1 != password2:
+ raise forms.ValidationError(_("The two password fields didn't match."))
+ return password2
+
+ def save(self, commit=True):
+ user = super(UserCreationForm, self).save(commit=False)
+ user.set_password(self.cleaned_data["password1"])
+ if commit:
+ user.save()
+ return user
-class AuthenticationForm(oldforms.Manipulator):
+class AuthenticationForm(forms.Form):
"""
Base class for authenticating users. Extend this to get a form that accepts
username/password logins.
"""
- def __init__(self, request=None):
+ username = forms.CharField(max_length=30)
+ password = forms.CharField(max_length=30, widget=forms.PasswordInput)
+
+ def __init__(self, request=None, *args, **kwargs):
"""
- If request is passed in, the manipulator will validate that cookies are
+ If request is passed in, the form will validate that cookies are
enabled. Note that the request (a HttpRequest object) must have set a
cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
- running this validator.
+ running this validation.
"""
self.request = request
- self.fields = [
- oldforms.TextField(field_name="username", length=15, max_length=30, is_required=True,
- validator_list=[self.isValidUser, self.hasCookiesEnabled]),
- oldforms.PasswordField(field_name="password", length=15, max_length=30, is_required=True),
- ]
self.user_cache = None
-
- def hasCookiesEnabled(self, field_data, all_data):
- if self.request and not self.request.session.test_cookie_worked():
- raise validators.ValidationError, _("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in.")
-
- def isValidUser(self, field_data, all_data):
- username = field_data
- password = all_data.get('password', None)
- self.user_cache = authenticate(username=username, password=password)
- if self.user_cache is None:
- raise validators.ValidationError, _("Please enter a correct username and password. Note that both fields are case-sensitive.")
- elif not self.user_cache.is_active:
- raise validators.ValidationError, _("This account is inactive.")
-
+ super(AuthenticationForm, self).__init__(*args, **kwargs)
+
+ def clean(self):
+ username = self.cleaned_data.get('username')
+ password = self.cleaned_data.get('password')
+
+ if username and password:
+ self.user_cache = authenticate(username=username, password=password)
+ if self.user_cache is None:
+ raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive."))
+ elif not self.user_cache.is_active:
+ raise forms.ValidationError(_("This account is inactive."))
+
+ # TODO: determine whether this should move to its own method.
+ if self.request:
+ if not self.request.session.test_cookie_worked():
+ raise forms.ValidationError(_("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in."))
+
+ return self.cleaned_data
+
def get_user_id(self):
if self.user_cache:
return self.user_cache.id
return None
-
+
def get_user(self):
return self.user_cache
-class PasswordResetForm(oldforms.Manipulator):
- "A form that lets a user request a password reset"
- def __init__(self):
- self.fields = (
- oldforms.EmailField(field_name="email", length=40, is_required=True,
- validator_list=[self.isValidUserEmail]),
- )
-
- def isValidUserEmail(self, new_data, all_data):
- "Validates that a user exists with the given e-mail address"
- self.users_cache = list(User.objects.filter(email__iexact=new_data))
+class PasswordResetForm(forms.Form):
+ email = forms.EmailField(max_length=40)
+
+ def clean_email(self):
+ """
+ Validates that a user exists with the given e-mail address.
+ """
+ email = self.cleaned_data["email"]
+ self.users_cache = User.objects.filter(email__iexact=email)
if len(self.users_cache) == 0:
- raise validators.ValidationError, _("That e-mail address doesn't have an associated user account. Are you sure you've registered?")
-
+ raise forms.ValidationError(_("That e-mail address doesn't have an associated user account. Are you sure you've registered?"))
+
def save(self, domain_override=None, email_template_name='registration/password_reset_email.html'):
- "Calculates a new password randomly and sends it to the user"
+ """
+ Calculates a new password randomly and sends it to the user.
+ """
from django.core.mail import send_mail
for user in self.users_cache:
new_pass = User.objects.make_random_password()
@@ -103,42 +121,69 @@ def save(self, domain_override=None, email_template_name='registration/password_
'domain': domain,
'site_name': site_name,
'user': user,
- }
- send_mail(_('Password reset on %s') % site_name, t.render(Context(c)), None, [user.email])
+ }
+ send_mail(_("Password reset on %s") % site_name,
+ t.render(Context(c)), None, [user.email])
-class PasswordChangeForm(oldforms.Manipulator):
- "A form that lets a user change his password."
- def __init__(self, user):
+class PasswordChangeForm(forms.Form):
+ """
+ A form that lets a user change his/her password.
+ """
+ old_password = forms.CharField(max_length=30, widget=forms.PasswordInput)
+ new_password1 = forms.CharField(max_length=30, widget=forms.PasswordInput)
+ new_password2 = forms.CharField(max_length=30, widget=forms.PasswordInput)
+
+ def __init__(self, user, *args, **kwargs):
self.user = user
- self.fields = (
- oldforms.PasswordField(field_name="old_password", length=30, max_length=30, is_required=True,
- validator_list=[self.isValidOldPassword]),
- oldforms.PasswordField(field_name="new_password1", length=30, max_length=30, is_required=True,
- validator_list=[validators.AlwaysMatchesOtherField('new_password2', _("The two 'new password' fields didn't match."))]),
- oldforms.PasswordField(field_name="new_password2", length=30, max_length=30, is_required=True),
- )
-
- def isValidOldPassword(self, new_data, all_data):
- "Validates that the old_password field is correct."
- if not self.user.check_password(new_data):
- raise validators.ValidationError, _("Your old password was entered incorrectly. Please enter it again.")
-
- def save(self, new_data):
- "Saves the new password."
- self.user.set_password(new_data['new_password1'])
- self.user.save()
-
-class AdminPasswordChangeForm(oldforms.Manipulator):
- "A form used to change the password of a user in the admin interface."
- def __init__(self, user):
+ super(PasswordChangeForm, self).__init__(*args, **kwargs)
+
+ def clean_old_password(self):
+ """
+ Validates that the old_password field is correct.
+ """
+ old_password = self.cleaned_data["old_password"]
+ if not self.user.check_password(old_password):
+ raise forms.ValidationError(_("Your old password was entered incorrectly. Please enter it again."))
+ return old_password
+
+ def clean_new_password2(self):
+ password1 = self.cleaned_data.get('new_password1')
+ password2 = self.cleaned_data.get('new_password2')
+ if password1 and password2:
+ if password1 != password2:
+ raise forms.ValidationError(_("The two password fields didn't match."))
+ return password2
+
+ def save(self, commit=True):
+ self.user.set_password(self.cleaned_data['new_password1'])
+ if commit:
+ self.user.save()
+ return self.user
+
+class AdminPasswordChangeForm(forms.Form):
+ """
+ A form used to change the password of a user in the admin interface.
+ """
+ password1 = forms.CharField(max_length=60, widget=forms.PasswordInput)
+ password2 = forms.CharField(max_length=60, widget=forms.PasswordInput)
+
+ def __init__(self, user, *args, **kwargs):
self.user = user
- self.fields = (
- oldforms.PasswordField(field_name='password1', length=30, max_length=60, is_required=True),
- oldforms.PasswordField(field_name='password2', length=30, max_length=60, is_required=True,
- validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]),
- )
-
- def save(self, new_data):
- "Saves the new password."
- self.user.set_password(new_data['password1'])
- self.user.save()
+ super(AdminPasswordChangeForm, self).__init__(*args, **kwargs)
+
+ def clean_password2(self):
+ password1 = self.cleaned_data.get('password1')
+ password2 = self.cleaned_data.get('password2')
+ if password1 and password2:
+ if password1 != password2:
+ raise forms.ValidationError(_("The two password fields didn't match."))
+ return password2
+
+ def save(self, commit=True):
+ """
+ Saves the new password.
+ """
+ self.user.set_password(self.cleaned_data["password1"])
+ if commit:
+ self.user.save()
+ return self.user
@@ -0,0 +1,8 @@
+from django.contrib.auth.tests.basic import BASIC_TESTS
+from django.contrib.auth.tests.forms import FORM_TESTS, PasswordResetFormTestCase
+
+__test__ = {
+ 'BASIC_TESTS': BASIC_TESTS,
+ 'PASSWORDRESET_TESTS': PasswordResetFormTestCase,
+ 'FORM_TESTS': FORM_TESTS,
+}
@@ -1,5 +1,6 @@
-"""
->>> from models import User, AnonymousUser
+
+BASIC_TESTS = """
+>>> from django.contrib.auth.models import User, AnonymousUser
>>> u = User.objects.create_user('testuser', 'test@example.com', 'testpw')
>>> u.has_usable_password()
True
Oops, something went wrong.

0 comments on commit ba2d0fe

Please sign in to comment.