article

Saturday, May 23, 2020

Django How to Create Change Password User


Django How to Create Change Password User

change password view using the built-in PasswordChangeForm


views.py
 
#views.py
from django.shortcuts import render, redirect
 
from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm

def change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # Important!
            messages.success(request, 'Your password was successfully updated!')
            return redirect('/password')
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'change_password.html', {'form': form })
urls.py
 
#urls.py
from django.contrib import admin  
from django.urls import path
from myapp import views  
from django.conf.urls import url

urlpatterns = [  
    path('admin/', admin.site.urls),  
    #path('',views.index),
 url(r'^password/$', views.change_password, name='change_password'),
]
change_password.html
//templates/change_password.html
<form method="post">
  {% csrf_token %}
  {{ form }}
  <button type="submit">Save changes</button>
</form>

First login using your account then
Run : http://127.0.0.1:8000/password/ to change password



Related Post