我有一个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})
Run Code Online (Sandbox Code Playgroud)
因此密码被更改,用户被重定向到仪表板页面,然后@login_required装饰器将它们重定向回登录屏幕.
密码表单在这里,虽然它非常简单.
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',
)
Run Code Online (Sandbox Code Playgroud)
Kos*_*tyn 23
对于django 1.9:
from django.contrib.auth import update_session_auth_hash
def password_change(request):
if request.method == 'POST':
form = PasswordChangeForm(user=request.user, data=request.POST)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
Run Code Online (Sandbox Code Playgroud)
必须在POST请求中提供以下字段:
请参阅https://docs.djangoproject.com/en/1.9/topics/auth/default/#session-invalidation-on-password-change上的详细文档
FeF*_*oFu 12
在Django 1.7中更改密码后,我的理解正在被注销.因此,如您所述,您需要在代码中重新授权用户.
请参阅发行说明:https: //docs.djangoproject.com/en/1.8/releases/1.7/#django-contrib-auth
以下是特定说明: "添加了AbstractBaseUser.get_session_auth_hash()方法,如果您的AUTH_USER_MODEL继承自AbstractBaseUser,则在启用SessionAuthenticationMiddleware时,更改用户密码会使旧会话无效.有关更多详细信息(包括升级注意事项),请参阅密码更改时的会话失效什么时候启用这个新的中间件."
请参阅文档:https: //docs.djangoproject.com/en/1.7/topics/auth/default/#session-invalidation-on-password-change
对于Django 1.8
只需拨打update_session_auth_hash
后set_password
,像这样:
from django.contrib.auth import update_session_auth_hash
request.user.set_password(form.cleaned_data['password'])
update_session_auth_hash(request, request.user)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7364 次 |
最近记录: |