Reputation: 45
I'm constructing site by Django.
I'm setting some authentications in this site, like Site Manager, Group Manager and Normal User.
When System Manager or Group Manager logged in, they could change the password of Normal Users as a part of system management.
In django, PasswordChangeForm or SetPasswordForm provide some user password change form. I think these forms are for changing password of users themselves.
Yes, I need that too. But I also need the form of changing the password of another users like django admin site.
How can I construct the form ?
I read the code of django's admin site.
I found AdminPasswordChangeForm, can I use this class ?
forms.py
class MyAdminPasswordChangeForm(AdminPasswordChangeForm):
def __init__(self, user, *args, **kwargs):
self.user = user
super().__init__(user, *args, **kwargs)
for field in self.fields.values():
field.widget.attrs['class'] = 'form-control'
views.py
class PasswordChange(PasswordChangeView):
form_class = MyAdminPasswordChangeForm
success_url = reverse_lazy('password_change_done')
template_name = 'accounts/password_change/password_admin_change.html'
def get(self, request, *args, **kwargs):
if 'user_id' in self.request.session:
user = User.objects.get(id=self.request.session['user_id'])
form_class = self.get_form_class()
form = form_class(user=user)
return self.render_to_response(self.get_context_data())
def get_form_class(self):
return self.form_class
Upvotes: 1
Views: 1862
Reputation: 91
you can use set_password() for change user passwords first you should select user with such code
user=User.objects.get(username=username)
then you can set password
user.set_password(password)
user.save()
Upvotes: 5