前端代碼搭建 主要利用的是bootstrap3中js插件里的模態框版塊 <li><a href="" data-toggle="modal" data-target=".bs-example-modal-lg">修改密碼</a></li> <div class="modal fade bs-exam ...
前端代碼搭建
主要利用的是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)