django.contrib.auth - PasswordChange 구현 참고

duo2208·2022년 1월 3일
0

Django

목록 보기
9/23
post-thumbnail
post-custom-banner

🦝 django/django/contrib/auth

PasswordChange 구현 참고


회원가입 및 로그인구현이 되어있음을 가정합니다.

# urls.py
from django.contrib.auth import views as auth_views

urlpatterns = [
    ...
    path('password_change/', views.password_change, name='password_change'),
]
# views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.views import PasswordChangeView as AuthPasswordChangeView
from django.shortcuts import redirect, render
from django.urls import reverse_lazy

class PasswordChangeView(LoginRequiredMixin, AuthPasswordChangeView):
    form_class = PasswordChangeForm
    success_url = reverse_lazy('password_change_done')
    template_name = 'accounts/password_change_form.html'

    def form_valid(self, form):
        messages.success(self.request, "비밀번호를 변경하였습니다.")
        # 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)

password_change  = PasswordChangeView.as_view()
# forms.py 
from django import forms
from django.contrib.auth.forms import PasswordChangeForm as AuthPasswordChangeForm

class PasswordChangeForm(AuthPasswordChangeForm):
    def clean_new_password2(self):
        old_password = self.cleaned_data["old_password"]
        new_password1 = self.cleaned_data["new_password1"]

        if old_password == new_password1:
            raise forms.ValidationError("새로운 비밀번호는 기존 비밀번호와 다르게 입력해주세요.")
        return new_password1
post-custom-banner

0개의 댓글