Thursday, January 27, 2022

thumbnail

Changing Password in Django

 

Changing Password in Django

In most of the recent day's applications, password changing is a very common settings functionality. The most common practice is to provide a form which takes the old password, new and confirm password. Here at first it matches the old one. If it is correct then new password is set. There is a built in form that we can use for changing password in Django. 'update_session_auth_hash' method is used for setting the new password.

urls.py

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

urlpatterns = [
    path('passwordChange', views.passwordChange, name='passwordChange'),
]


views.py

from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm

 

def passwordChange(request):
    form = PasswordChangeForm(user=request.user)
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)
            messages.info(
                request, 'Your password was successfully updated!')
            return redirect('passwordChange')
        else:
            messages.error(request, 'Please correct your informations')
    context = {'form':form}
    return render(request,'passwordChange.html',context)

               

passwordChange.html


        <form method = 'POST' action=''>
                {% csrf_token %}
                {{ form }}
                <button type="submit" class="">
                  Confirm
                </button>
            </form>


 

Tags :

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments