Django 重置密码

前提:用户已经登录
1,模板参考
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>故事其实很短</title>
    <link rel="icon" href="/static/images/favicon.ico">
    <link href="/static/plugins/bootstrap-5.0.0-beta1-dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="/static/css/master.css" rel="stylesheet">
</head>

<body>
    <form action="" method="post" class="forget-password-form">
        {% csrf_token %}
        <h4>Reset Password</h4>
        <h6>Username: {{username}}</h6>
        <input type="password" name="current_passwd" placeholder="current password" class="forget-password-input" />
        <input type="password" name="new_passwd" placeholder="new password" class="forget-password-input" />
        <input type="password" name="confirm_passwd" placeholder="confirm password" class="forget-password-input" />
        <input type="submit" value="RESET" class="login-button" />
        <span class="forget-password-tips">{{reset_password_tips}}</span>
    </form>
</body>
</html>
0
 
2,重置密码视图
vim app01/views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.contrib import auth
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
#from django.conf import settings
#from django.core.mail import send_mail
#import random
#import string
#from django.contrib.auth.hashers import make_password


# reset password
@login_required
def reset_password(request):
    if request.method == "GET":
        return render(request, "reset_password.html", {"username": request.user.username})
    else:
        current_password = request.POST.get("current_passwd")
        new_password = request.POST.get("new_passwd")
        confirm_password = request.POST.get("confirm_passwd")
        # check current password if correct, check_password(raw_password)
        if request.user.check_password(raw_password=current_password):
            if new_password == confirm_password:
                request.user.set_password(confirm_password)
                request.user.save()
                return render(request, "reset_password.html", {"reset_password_tips": "Your password has changed!"})
            else:
                return render(request, "reset_password.html", {"reset_password_tips": "Two password don't match!"})
        else:
            return render(request, "reset_password.html", {"reset_password_tips": "Your current password is not correct!"})

 

检查现有密码是否正确
request.user.check_password(raw_password='当前密码')
更新密码
request.user.set_password('新密码')
request.user.save()
3, URL设置
vim app01/urls.py
from django.urls import path
from . import views

urlpatterns = [
  
    path('reset_password/', views.reset_password),
]

 

参考博客:

https://www.cnblogs.com/ryxiong-blog/articles/10986867.html

 
posted @ 2021-05-09 11:51  zhangrayhung  阅读(234)  评论(0编辑  收藏  举报