Django2.1使用内置PasswordChangeView修改密码

Django2.1使用内置PasswordChangeView修改密码
在Django2.X以前的版本中,修改密码使用:

from django.contrib.auth import views as auth_views
url(r'^password-change/$', auth_views.password_change,
    {"post_change_redirect":"/account/password_change_done",
     'template_name': 'account/password_change_form.html'},
    name='password_change'),

但是在Django2.1中,之前更改密码的函数被换成了更改密码的类:

class PasswordChangeView(PasswordContextMixin, FormView):
    form_class = PasswordChangeForm
    success_url = reverse_lazy('password_change_done')
    template_name = 'registration/password_change_form.html'
    title = _('Password change')

    @method_decorator(sensitive_post_parameters())
    @method_decorator(csrf_protect)
    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)

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

    def form_valid(self, form):
        form.save()
        # Updating the password logs out all other sessions for the user
        # except the current one.
        update_session_auth_hash(self.request, form.user)
        return super().form_valid(form)

原来的方式已经行不通了,查看Django2.1官方文档,找到如下使用方法:

说了可以自定义模板,但是没说修改成功怎么跳转到自定义模板。
查看源码,得出了以下方法:

from django.contrib.auth import views as auth_views
from django.urls import reverse_lazy

app_name = 'account'

urlpatterns = [
   
    path('password-change/', auth_views.PasswordChangeView.as_view(
        template_name='account/password_change_form.html',
        success_url=reverse_lazy('account:password_change_done')), name='password_change'),
    path('password_change_done/', auth_views.PasswordChangeDoneView.as_view(
        template_name='account/password_change_done.html'), name='password_change_done'),

]

运行,成功执行。
Django2.1改动的不少,一时半会还是不好适应的。
但还是强烈推荐大家去学习使用Django2.1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值