前言
在Django中有大量的通用類視圖,例如ListView,DetailView,CreateView,UpdateView等等,將所有重復的增刪改查代碼抽象成一個通用類,只需要配置極少量的代碼即可實現功能。
使用通用類視圖完成找回密碼功能
首先引入
from django.contrib.auth.views import PasswordResetView, PasswordResetConfirmView, / PasswordResetDoneView, PasswordChangeView, PasswordChangeDoneView, / PasswordResetCompleteView
配置如下:
class MyPasswordResetView(PasswordResetView): """重置密碼視圖""" template_name = 'users/registration/forget_pwd.html' form_class = ForgetForm success_url = reverse_lazy("users:password_reset_done") email_template_name = 'users/registration/password_reset_email.html'class MyPasswordResetConfirmView(PasswordResetConfirmView): """重置密碼頁面,輸入兩次密碼""" template_name = 'users/registration/password_change_form.html' success_url = reverse_lazy('users:password_reset_complete')class MyPasswordResetDoneView(PasswordResetDoneView): """發送確認重置郵件""" template_name = 'users/registration/password_reset_done.html'class MyPasswordResetCompleteView(PasswordResetCompleteView): """完成重置密碼""" template_name = 'users/registration/password_change_done.html'
其中忘記密碼,填寫郵箱的模板forget_pwd.html模板如下:
<form method="post" class="form-validate" action="{% url 'users:password_reset' %}"> <div class="form-group"> <input type="text" name="email" required data-msg="請輸入您的郵箱" class="input-material"> <label for="login-username" class="label-material">郵箱</label> {% if form.errors %} <div >郵箱輸入錯誤</div> {% endif %} </div> {% csrf_token %} <button type="submit" href="#" rel="external nofollow" class="btn btn-primary">發送確認郵件</button> <!-- This should be submit button but I replaced it with <a> for demo purposes--> </form>
其中輸入新密碼模板password_change_form.html頁面如下:
<form method="post"> {% csrf_token %} {{ form|crispy }} <div class="form-group"> <button type="submit" class="btn btn-primary button-submit">確認更改</button> </div></form>
其中重置密碼郵件發送成功的模板password_reset_done.html如下:
<div class="col-lg-6 bg-white"> <div class="form d-flex align-items-center"> <div class="content"> <h1>重置密碼郵件發送成功!</h1> </div> </div> </div>
其中密碼重置成功password_change_done.html如下:
<div class="container"> <div class="row"> <div class="col-md-6 offset-md-3"> <h1>重置密碼成功!</h1> <a href="{% url 'index' %}" rel="external nofollow" >回到首頁</a> </div> </div> </div>
新聞熱點
疑難解答