Posted in Python onDecember 17, 2019
前言
在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 id="login-username" type="text" name="email" required data-msg="请输入您的邮箱" class="input-material"> <label for="login-username" class="label-material">邮箱</label> {% if form.errors %} <div style="color: red">邮箱输入错误</div> {% endif %} </div> {% csrf_token %} <button type="submit" id="login" 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 id="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>
最后配置路由
path('password/reset/', view=MyPasswordResetView.as_view(), name='password_reset'), # password_reset path('password/reset/done/', MyPasswordResetDoneView.as_view(), name='password_reset_done'), # password_reset_done url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', view=MyPasswordResetConfirmView.as_view(), name='password_reset_confirm'), # reset path('reset/done/', MyPasswordResetCompleteView.as_view(), name='password_reset_complete'),
效果如下:
以上这篇Django通用类视图实现忘记密码重置密码功能示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。
Django通用类视图实现忘记密码重置密码功能示例
- Author -
Pykk2019声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@