更改密码后显示确认消息



用户成功更改密码后,我会将该用户保留在名为password_change的同一页面上。

url.py

path('password_change/', auth_views.PasswordChangeView.as_view(success_url=reverse_lazy('password_change')), name='password_change'),

我尝试使用消息框架:

视图.py

def password_change(request):
password_form = PasswordChangeForm(instance = request.user, data = request.POST)
if request.method == 'POST':
if password_form.is_valid():
password_form.save()
update_session_auth_hash(request, password_form.user)  # <-- keep the user loged after password change
messages.success(request, 'Your password has been updated', extra_tags='safe')
return render(request, 'registration/password_change_form.html', {'password_form': password_form})

在我的html:中

{% if messages %}
{% for message in messages %}
<p class='{{ message.tags }}'>{{ message }}</p>
{% endfor %}
{% endif %}

我试过了:

视图.py

def password_change(request):
success = False;
password_form = PasswordChangeForm(instance = request.user, data = request.POST)
if request.method == 'POST':
if password_form.is_valid():
password_form.save()
update_session_auth_hash(request, password_form.user)  # <-- keep the user loged after password change
success = True;
return render(request, 'registration/password_change_form.html', {'password_form': password_form, 'success': success})

在我的html:中

{% if success %}
<div>Password changed !!!</div>
{% endif %}

密码已更改,但我无法显示消息来庆祝这一巨大成功。

可能是您的成功变量没有将其值设置为"True"。在第二种方法中,尝试将success=True置于update_session_auth_hash(request, password_form.user)行之前

我找到了一个可以接受的解决方案。在这个例子中,我重定向到另一个页面,但如果我想在同一页面上重定向,原理是一样的:

urls.py:

path('password_change/', auth_views.PasswordChangeView.as_view(), name = 'password_change'),
path('edit_profile_alt/', views.CustomPasswordChangeDoneView.as_view(), name = 'password_change_done'),

视图.py:

@login_required(redirect_field_name = 'login')
def password_change(request):
password_form = PasswordChangeForm(instance = request.user, data = request.POST)
if request.method == 'POST':
if password_form.is_valid():
password_form.save()
update_session_auth_hash(request, password_form.user)  # <-- keep the user loged after password change

class CustomPasswordChangeDoneView(PasswordChangeDoneView):
template_name = 'appName/edit_profile.html'
extra_context = {'done': 'done'}

html模板:

{% if done %}
<p>
You have a changed your password.
</p>
{% else %}

如果你想做同样的事情,读起来很好:https://docs.djangoproject.com/en/2.1/topics/auth/default/#django.contrib.auth.views.PasswordChangeDoneView

相关内容

  • 没有找到相关文章

最新更新