更改密码后显示确认消息

时间:2018-11-05 23:43:14

标签: django django-forms

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

url.py

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

我尝试将消息框架用于:

views.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 %}

我尝试过:

views.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 %}

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

2 个答案:

答案 0 :(得分:0)

可能是您的成功变量未将其值设置为“ True”。 在第二种方法中,尝试将success=True放在行update_session_auth_hash(request, password_form.user)

之前

答案 1 :(得分:0)

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

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'),

views.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