修改密码弹出框搭建
前端代码搭建
主要利用的是bootstrap3中js插件里的模态框版块
<li><a href="" data-toggle="modal" data-target=".bs-example-modal-lg">修改密码</a></li>
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h3 class="text-center">修改密码</h3>
<div class="form-group">
<label for="">用户名:</label>
<input type="text" disabled value="{{ request.user.username }}" class="form-control" id="id_username">
</div>
<div class="form-group">
<label for="">原密码:</label>
<input type="text" id="old_password" class="form-control">
</div>
<div class="form-group">
<label for="">新密码:</label>
<input type="password" id="id_password" class="form-control">
</div>
<div class="form-group">
<label for="">新密码:</label>
<input type="text" id="confirm_password" class="form-control">
</div>
<span style="color:red;" id="error"></span>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal" >取消</button>
<button type="button" class="btn btn-primary" id="commit">修改</button>
</div>
</div>
</div>
<br>
</div>
</div>
</div>
<script>
$("#commit").click(function (){
$.ajax({
type:"post",
url:"/set_password/",
data:{
"username":$("#id_username").val(),
"old_password":$("#old_password").val(),
"password":$("#id_password").val(),
"confirm_password":$("#confirm_password").val(),
"csrfmiddlewaretoken":"{{ csrf_token }}",
},
success:function (args){
if (args.code==1000){
window.location.reload();
}else {
$("#error").text(args.msg)
}
}
})
})
</script>
后端接收修改密码数据并提供错误提示
注意修改密码的视图函数必须是登录用户才能使用,所以需要一个@login_required装饰器
@login_required
def set_password(request):
# 1.判断是否为ajax请求
if request.method == "POST":
back_dic = {"code":1000,"msg":""}
# 2.获取用户修改密码提交的数据
username = request.POST.get("username")
old_password = request.POST.get("old_password")
password = request.POST.get("password")
confirm_password = request.POST.get("confirm_password")
# 3.对比原密码是否正确
is_right = request.user.check_password(old_password)
if is_right:
# 4.判断两次密码是否一致
if password == confirm_password:
# 5.一致则修改密码
request.user.set_password(password)
request.user.save()
else:
back_dic["code"] = 1001
back_dic["msg"] = "两次密码不一致"
else:
back_dic["code"] = 1002
back_dic["msg"] = "原密码不正确"
return JsonResponse(back_dic)