我对Django用户更改密码有问题——我在Django建立了几个生产站点,大约一年(或1.8年)没有,但我不记得以前有过这个问题。
摘要
当用户更改其密码时,该用户将注销,但密码已成功更改。
详细信息
我有一个允许用户更改密码的视图,我使用的是标准的django表单和auth框架,并且强调:更改密码是有效的,它只是将用户注销,以便他们必须再次登录。
实际上我并不介意这样,我更希望用户通过消息更新重定向到他们的仪表板,如果我需要在代码中重新验证用户,那么我会,只是看起来有点笨拙。
以下是我的视图函数:@login_required
def user_change_password(request):
"""Allows a user to change their password"""
if request.method == "POST":
form = SubscriberPasswordForm(request.POST)
if form.is_valid():
try:
request.user.set_password(form.cleaned_data['password'])
request.user.save()
except Exception, err:
print "Error changing password: {}".format(err)
messages.add_message(request, messages.ERROR, 'The password could not be changed, please try again '
'later. This admins have been notified of this error.')
else:
#this outputs True
print request.user.is_authenticated()
messages.add_message(request, messages.INFO, 'Your password has been changed successfully')
return HttpResponseRedirect("/accounts/dashboard/")
else:
form = SubscriberPasswordForm()
return render(request, "accounts/change-password.html", {"form": form})
因此,密码被更改,用户被重定向到仪表板页面,@login所需的装饰器然后将它们重定向回登录屏幕。
密码表单在这里,尽管它非常简单。class SubscriberPasswordForm(forms.Form):
password = forms.CharField(widget=forms.PasswordInput)
cpassword = forms.CharField(widget=forms.PasswordInput)
def clean_cpassword(self):
password1 = self.cleaned_data.get("password")
password2 = self.cleaned_data.get("cpassword")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)