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

你可能感兴趣的:(Django2.1使用内置PasswordChangeView修改密码)