diff options
Diffstat (limited to 'django/contrib/auth')
| -rw-r--r-- | django/contrib/auth/admin.py | 66 | ||||
| -rw-r--r-- | django/contrib/auth/forms.py | 233 | ||||
| -rw-r--r-- | django/contrib/auth/models.py | 25 | ||||
| -rw-r--r-- | django/contrib/auth/tests/__init__.py | 8 | ||||
| -rw-r--r-- | django/contrib/auth/tests/basic.py (renamed from django/contrib/auth/tests.py) | 8 | ||||
| -rw-r--r-- | django/contrib/auth/tests/forms.py | 135 | ||||
| -rw-r--r-- | django/contrib/auth/views.py | 91 |
7 files changed, 418 insertions, 148 deletions
diff --git a/django/contrib/auth/admin.py b/django/contrib/auth/admin.py new file mode 100644 index 0000000000..998692a6cb --- /dev/null +++ b/django/contrib/auth/admin.py @@ -0,0 +1,66 @@ +from django.contrib.auth.models import User, Group +from django.core.exceptions import PermissionDenied +from django import oldforms, template +from django.shortcuts import render_to_response +from django.http import HttpResponseRedirect +from django.utils.translation import ugettext, ugettext_lazy as _ +from django.contrib import admin + +class GroupAdmin(admin.ModelAdmin): + search_fields = ('name',) + ordering = ('name',) + filter_horizontal = ('permissions',) + +class UserAdmin(admin.ModelAdmin): + fieldsets = ( + (None, {'fields': ('username', 'password')}), + (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}), + (_('Permissions'), {'fields': ('is_staff', 'is_active', 'is_superuser', 'user_permissions')}), + (_('Important dates'), {'fields': ('last_login', 'date_joined')}), + (_('Groups'), {'fields': ('groups',)}), + ) + list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff') + list_filter = ('is_staff', 'is_superuser') + search_fields = ('username', 'first_name', 'last_name', 'email') + ordering = ('username',) + filter_horizontal = ('user_permissions',) + + def add_view(self, request): + # avoid a circular import. see #6718. + from django.contrib.auth.forms import UserCreationForm + if not self.has_change_permission(request): + raise PermissionDenied + if request.method == 'POST': + 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) + return HttpResponseRedirect(request.path) + else: + request.user.message_set.create(message=msg + ' ' + ugettext("You may edit it again below.")) + return HttpResponseRedirect('../%s/' % new_user.id) + else: + form = UserCreationForm() + return render_to_response('admin/auth/user/add_form.html', { + 'title': _('Add user'), + 'form': form, + 'is_popup': '_popup' in request.REQUEST, + 'add': True, + 'change': False, + 'has_add_permission': True, + 'has_delete_permission': False, + 'has_change_permission': True, + 'has_file_field': False, + 'has_absolute_url': False, + 'auto_populated_fields': (), + 'opts': User._meta, + 'save_as': False, + 'username_help_text': User._meta.get_field('username').help_text, + 'root_path': self.admin_site.root_path, + }, context_instance=template.RequestContext(request)) + +admin.site.register(Group, GroupAdmin) +admin.site.register(User, UserAdmin) + diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py index 47a974cacd..f63dc7b854 100644 --- a/django/contrib/auth/forms.py +++ b/django/contrib/auth/forms.py @@ -3,88 +3,106 @@ from django.contrib.auth import authenticate from django.contrib.sites.models import Site from django.template import Context, loader from django.core import validators -from django import oldforms -from django.utils.translation import ugettext as _ +from django import newforms as forms +from django.utils.translation import ugettext_lazy 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(label=_("Username"), max_length=30) + password = forms.CharField(label=_("Password"), 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(label=_("E-mail"), 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 @@ class PasswordResetForm(oldforms.Manipulator): '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(label=_("Old password"), max_length=30, widget=forms.PasswordInput) + new_password1 = forms.CharField(label=_("New password"), max_length=30, widget=forms.PasswordInput) + new_password2 = forms.CharField(label=_("New password confirmation"), 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() + 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(oldforms.Manipulator): - "A form used to change the password of a user in the admin interface." - def __init__(self, user): +class AdminPasswordChangeForm(forms.Form): + """ + A form used to change the password of a user in the admin interface. + """ + password1 = forms.CharField(label=_("Password"), max_length=60, widget=forms.PasswordInput) + password2 = forms.CharField(label=_("Password (again)"), 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 diff --git a/django/contrib/auth/models.py b/django/contrib/auth/models.py index 379a9f4c64..a0ed4f366f 100644 --- a/django/contrib/auth/models.py +++ b/django/contrib/auth/models.py @@ -91,16 +91,12 @@ class Group(models.Model): Beyond permissions, groups are a convenient way to categorize users to apply some label, or extended functionality, to them. For example, you could create a group 'Special users', and you could write code that would do special things to those users -- such as giving them access to a members-only portion of your site, or sending them members-only e-mail messages. """ name = models.CharField(_('name'), max_length=80, unique=True) - permissions = models.ManyToManyField(Permission, verbose_name=_('permissions'), blank=True, filter_interface=models.HORIZONTAL) + permissions = models.ManyToManyField(Permission, verbose_name=_('permissions'), blank=True) class Meta: verbose_name = _('group') verbose_name_plural = _('groups') - - class Admin: - search_fields = ('name',) - ordering = ('name',) - + def __unicode__(self): return self.name @@ -147,26 +143,13 @@ class User(models.Model): date_joined = models.DateTimeField(_('date joined'), default=datetime.datetime.now) groups = models.ManyToManyField(Group, verbose_name=_('groups'), blank=True, help_text=_("In addition to the permissions manually assigned, this user will also get all permissions granted to each group he/she is in.")) - user_permissions = models.ManyToManyField(Permission, verbose_name=_('user permissions'), blank=True, filter_interface=models.HORIZONTAL) + user_permissions = models.ManyToManyField(Permission, verbose_name=_('user permissions'), blank=True) objects = UserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') - - class Admin: - fields = ( - (None, {'fields': ('username', 'password')}), - (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}), - (_('Permissions'), {'fields': ('is_staff', 'is_active', 'is_superuser', 'user_permissions')}), - (_('Important dates'), {'fields': ('last_login', 'date_joined')}), - (_('Groups'), {'fields': ('groups',)}), - ) - list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff') - list_filter = ('is_staff', 'is_superuser') - search_fields = ('username', 'first_name', 'last_name', 'email') - ordering = ('username',) - + def __unicode__(self): return self.username diff --git a/django/contrib/auth/tests/__init__.py b/django/contrib/auth/tests/__init__.py new file mode 100644 index 0000000000..6242303f46 --- /dev/null +++ b/django/contrib/auth/tests/__init__.py @@ -0,0 +1,8 @@ +from django.contrib.auth.tests.basic import BASIC_TESTS, PasswordResetTest +from django.contrib.auth.tests.forms import FORM_TESTS + +__test__ = { + 'BASIC_TESTS': BASIC_TESTS, + 'PASSWORDRESET_TESTS': PasswordResetTest, + 'FORM_TESTS': FORM_TESTS, +} diff --git a/django/contrib/auth/tests.py b/django/contrib/auth/tests/basic.py index ea1ac26c21..76dbdc9cb9 100644 --- a/django/contrib/auth/tests.py +++ b/django/contrib/auth/tests/basic.py @@ -1,4 +1,5 @@ -""" + +BASIC_TESTS = """ >>> from django.contrib.auth.models import User, AnonymousUser >>> u = User.objects.create_user('testuser', 'test@example.com', 'testpw') >>> u.has_usable_password() @@ -60,14 +61,15 @@ from django.core import mail class PasswordResetTest(TestCase): fixtures = ['authtestdata.json'] urls = 'django.contrib.auth.urls' + def test_email_not_found(self): "Error is raised if the provided email address isn't currently registered" response = self.client.get('/password_reset/') self.assertEquals(response.status_code, 200) response = self.client.post('/password_reset/', {'email': 'not_a_real_email@email.com'}) - self.assertContains(response, "That e-mail address doesn't have an associated user account") + self.assertContains(response, "That e-mail address doesn't have an associated user account") self.assertEquals(len(mail.outbox), 0) - + def test_email_found(self): "Email is sent if a valid email address is provided for password reset" response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'}) diff --git a/django/contrib/auth/tests/forms.py b/django/contrib/auth/tests/forms.py new file mode 100644 index 0000000000..1e1e0a95d4 --- /dev/null +++ b/django/contrib/auth/tests/forms.py @@ -0,0 +1,135 @@ + +FORM_TESTS = """ +>>> from django.contrib.auth.models import User +>>> from django.contrib.auth.forms import UserCreationForm, AuthenticationForm +>>> from django.contrib.auth.forms import PasswordChangeForm + +The user already exists. + +>>> user = User.objects.create_user("jsmith", "jsmith@example.com", "test123") +>>> data = { +... 'username': 'jsmith', +... 'password1': 'test123', +... 'password2': 'test123', +... } +>>> form = UserCreationForm(data) +>>> form.is_valid() +False +>>> form["username"].errors +[u'A user with that username already exists.'] + +The username contains invalid data. + +>>> data = { +... 'username': 'jsmith@example.com', +... 'password1': 'test123', +... 'password2': 'test123', +... } +>>> form = UserCreationForm(data) +>>> form.is_valid() +False +>>> form["username"].errors +[u'This value must contain only letters, numbers and underscores.'] + +The verification password is incorrect. + +>>> data = { +... 'username': 'jsmith2', +... 'password1': 'test123', +... 'password2': 'test', +... } +>>> form = UserCreationForm(data) +>>> form.is_valid() +False +>>> form["password2"].errors +[u"The two password fields didn't match."] + +The success case. + +>>> data = { +... 'username': 'jsmith2', +... 'password1': 'test123', +... 'password2': 'test123', +... } +>>> form = UserCreationForm(data) +>>> form.is_valid() +True +>>> form.save() +<User: jsmith2> + +The user submits an invalid username. + +>>> data = { +... 'username': 'jsmith_does_not_exist', +... 'password': 'test123', +... } + +>>> form = AuthenticationForm(None, data) +>>> form.is_valid() +False +>>> form.non_field_errors() +[u'Please enter a correct username and password. Note that both fields are case-sensitive.'] + +The user is inactive. + +>>> data = { +... 'username': 'jsmith', +... 'password': 'test123', +... } +>>> user.is_active = False +>>> user.save() +>>> form = AuthenticationForm(None, data) +>>> form.is_valid() +False +>>> form.non_field_errors() +[u'This account is inactive.'] + +>>> user.is_active = True +>>> user.save() + +The success case + +>>> form = AuthenticationForm(None, data) +>>> form.is_valid() +True +>>> form.non_field_errors() +[] + +The old password is incorrect. + +>>> data = { +... 'old_password': 'test', +... 'new_password1': 'abc123', +... 'new_password2': 'abc123', +... } +>>> form = PasswordChangeForm(user, data) +>>> form.is_valid() +False +>>> form["old_password"].errors +[u'Your old password was entered incorrectly. Please enter it again.'] + +The two new passwords do not match. + +>>> data = { +... 'old_password': 'test123', +... 'new_password1': 'abc123', +... 'new_password2': 'abc', +... } +>>> form = PasswordChangeForm(user, data) +>>> form.is_valid() +False +>>> form["new_password2"].errors +[u"The two password fields didn't match."] + +The success case. + +>>> data = { +... 'old_password': 'test123', +... 'new_password1': 'abc123', +... 'new_password2': 'abc123', +... } +>>> form = PasswordChangeForm(user, data) +>>> form.is_valid() +True + +""" diff --git a/django/contrib/auth/views.py b/django/contrib/auth/views.py index 524710327a..0a52240631 100644 --- a/django/contrib/auth/views.py +++ b/django/contrib/auth/views.py @@ -1,42 +1,42 @@ -from django import oldforms from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import AuthenticationForm -from django.contrib.auth.forms import PasswordResetForm, PasswordChangeForm +from django.contrib.auth.forms import PasswordResetForm, PasswordChangeForm, AdminPasswordChangeForm +from django.core.exceptions import PermissionDenied +from django.shortcuts import render_to_response, get_object_or_404 from django.contrib.sites.models import Site, RequestSite from django.http import HttpResponseRedirect -from django.shortcuts import render_to_response from django.template import RequestContext from django.utils.http import urlquote +from django.utils.html import escape from django.utils.translation import ugettext as _ +from django.contrib.auth.models import User +import re def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME): "Displays the login form and handles the login action." - manipulator = AuthenticationForm() redirect_to = request.REQUEST.get(redirect_field_name, '') - if request.POST: - errors = manipulator.get_validation_errors(request.POST) - if not errors: + if request.method == "POST": + form = AuthenticationForm(data=request.POST) + if form.is_valid(): # Light security check -- make sure redirect_to isn't garbage. if not redirect_to or '//' in redirect_to or ' ' in redirect_to: from django.conf import settings redirect_to = settings.LOGIN_REDIRECT_URL from django.contrib.auth import login - login(request, manipulator.get_user()) + login(request, form.get_user()) if request.session.test_cookie_worked(): request.session.delete_test_cookie() return HttpResponseRedirect(redirect_to) else: - errors = {} + form = AuthenticationForm(request) request.session.set_test_cookie() - if Site._meta.installed: current_site = Site.objects.get_current() else: current_site = RequestSite(request) - return render_to_response(template_name, { - 'form': oldforms.FormWrapper(manipulator, request.POST, errors), + 'form': form, redirect_field_name: redirect_to, 'site_name': current_site.name, }, context_instance=RequestContext(request)) @@ -66,13 +66,11 @@ def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_N return HttpResponseRedirect('%s?%s=%s' % (login_url, urlquote(redirect_field_name), urlquote(next))) def password_reset(request, is_admin_site=False, template_name='registration/password_reset_form.html', - email_template_name='registration/password_reset_email.html'): - new_data, errors = {}, {} - form = PasswordResetForm() - if request.POST: - new_data = request.POST.copy() - errors = form.get_validation_errors(new_data) - if not errors: + email_template_name='registration/password_reset_email.html', + password_reset_form=PasswordResetForm): + if request.method == "POST": + form = password_reset_form(request.POST) + if form.is_valid(): if is_admin_site: form.save(domain_override=request.META['HTTP_HOST']) else: @@ -81,24 +79,57 @@ def password_reset(request, is_admin_site=False, template_name='registration/pas else: form.save(domain_override=RequestSite(request).domain, email_template_name=email_template_name) return HttpResponseRedirect('%sdone/' % request.path) - return render_to_response(template_name, {'form': oldforms.FormWrapper(form, new_data, errors)}, - context_instance=RequestContext(request)) + else: + form = password_reset_form() + return render_to_response(template_name, { + 'form': form, + }, context_instance=RequestContext(request)) def password_reset_done(request, template_name='registration/password_reset_done.html'): return render_to_response(template_name, context_instance=RequestContext(request)) def password_change(request, template_name='registration/password_change_form.html'): - new_data, errors = {}, {} - form = PasswordChangeForm(request.user) - if request.POST: - new_data = request.POST.copy() - errors = form.get_validation_errors(new_data) - if not errors: - form.save(new_data) + if request.method == "POST": + form = PasswordChangeForm(request.user, request.POST) + if form.is_valid(): + form.save() return HttpResponseRedirect('%sdone/' % request.path) - return render_to_response(template_name, {'form': oldforms.FormWrapper(form, new_data, errors)}, - context_instance=RequestContext(request)) + else: + form = PasswordChangeForm(request.user) + return render_to_response(template_name, { + 'form': form, + }, context_instance=RequestContext(request)) password_change = login_required(password_change) def password_change_done(request, template_name='registration/password_change_done.html'): return render_to_response(template_name, context_instance=RequestContext(request)) + +# TODO: move to admin.py in the ModelAdmin +def user_change_password(request, id): + if not request.user.has_perm('auth.change_user'): + raise PermissionDenied + user = get_object_or_404(User, pk=id) + if request.method == 'POST': + form = AdminPasswordChangeForm(user, request.POST) + if form.is_valid(): + new_user = form.save() + msg = _('Password changed successfully.') + request.user.message_set.create(message=msg) + return HttpResponseRedirect('..') + else: + form = AdminPasswordChangeForm(user) + return render_to_response('admin/auth/user/change_password.html', { + 'title': _('Change password: %s') % escape(user.username), + 'form': form, + 'is_popup': '_popup' in request.REQUEST, + 'add': True, + 'change': False, + 'has_delete_permission': False, + 'has_change_permission': True, + 'has_absolute_url': False, + 'opts': User._meta, + 'original': user, + 'save_as': False, + 'show_save': True, + 'root_path': re.sub('auth/user/(\d+)/password/$', '', request.path), + }, context_instance=RequestContext(request)) |
