密码更改后显示消息? [英] Show message after password change?

查看:140
本文介绍了密码更改后显示消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是默认更改密码机制由django提供。

I'm using the default change password mechanism provided by django.

我正在使用 post_change_redirect 将提交的表单直接返回到我的设置页面,但是我想显示一条消息,以向用户保证操作已成功。由于密码更改成功,我如何检测是否到达我的设置视图,并添加了一条消息?

I'm using post_change_redirect to have the submitted form go straight back to my settings page, however I'd like to show a message to reassure the user that the operation has been successful. How can I detect whether I'm arriving in my settings view as the result of a successful password change, and add a message to that effect?

推荐答案

我不建议在设置视图中查看用户是否通过密码更改到达。我认为,理想情况下,所有的密码更改逻辑都包含在同一个地方。这使得更容易找到逻辑,并且不需要设置视图来了解密码更改视图(因此您可以轻松地更改逻辑以将用户重定向到其他地方)。

I wouldn't recommend checking in the settings view whether a user has arrived via a password change. I think that ideally, all of the logic for password changes is contained in the same place. This makes it easier to find the logic, and doesn't require the settings view to know about the password change view (so you could easily change the logic to redirect the user somewhere else).

最好的办法是根据 PasswordChangeForm 编写自己的视图,而不是使用内置的 password_change 视图。使用此方法,您可以使用消息框架显示成功消息。 (您还必须启用消息框架并将其标记放在您的视图中。)

Your best bet is to write your own view based on PasswordChangeForm instead of using the built-in password_change view. With this approach, you can use the message framework to display a success message. (You'll also have to enable the message framework and put its markup in your views.)

例如,如果要显示一条简单的消息并重定向到您的URL模式名为'settings',您可以编写如下视图:

For example, if you wanted to display a simple message and redirect back to your URL pattern named 'settings', you could write a view such as this one:

from django.contrib import messages
from django.contrib.auth.forms import PasswordChangeForm
from django.core.urlresolvers import reverse_lazy
from django.views.generic import FormView


class PasswordChangeView(FormView):
    template_name = 'registration/password_change_form.html'
    form_class = PasswordChangeForm
    success_url = reverse_lazy('settings')

    def get_form_kwargs(self):
        kwargs = super(PasswordChangeView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

    def form_valid(self, form):
        form.save()
        messages.success(self.request, "Your password has been changed.")
        return super(FormView, self).form_valid(form)

希望将来, password_change 视图将以类为基础,允许使用相同的行为更少的样板。

Hopefully, the password_change view will be made class-based in the future, allowing the same behavior with even less boilerplate.

这篇关于密码更改后显示消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆