How to allow users to change their own passwords in Django?

前端 未结 9 1392
梦如初夏
梦如初夏 2021-01-30 03:57

Can any one point me to code where users can change their own passwords in Django?

9条回答
  •  死守一世寂寞
    2021-01-30 04:33

    This tutorial shows how to do it with function based views:

    View file:

    from django.contrib import messages
    from django.contrib.auth import update_session_auth_hash
    from django.contrib.auth.forms import PasswordChangeForm
    from django.shortcuts import render, redirect
    
    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('change_password')
            else:
                messages.error(request, 'Please correct the error below.')
        else:
            form = PasswordChangeForm(request.user)
        return render(request, 'accounts/change_password.html', {
            'form': form
        })
    

    Url file:

    from django.conf.urls import url
    from myproject.accounts import views
    
    urlpatterns = [
        url(r'^password/$', views.change_password, name='change_password'),
    ]
    

    And finally, the template:

    {% csrf_token %} {{ form }}

提交回复
热议问题