美文网首页Django在线教育平台
【Django在线教育平台】06.找回密码,实现忘记密码及重置密

【Django在线教育平台】06.找回密码,实现忘记密码及重置密

作者: 吾星喵 | 来源:发表于2019-06-04 14:32 被阅读48次

    专题:Django2.0.8+xadmin2实现在线学习网站

    Django2.0.8+xadmin2实现在线学习网站,课程、讲师、机构、用户收藏功能。GitHub地址:https://github.com/xyliurui/OnlineLearningPlatform ;Django版本:2.0.8

    更多内容请点击 我的博客 查看,欢迎来访。

    找回密码

    忘记密码

    忘记密码模板forgetpwd.html

    创建,或者拷贝到对应目录

    <h3>密码重置</h3>
    <p>密码忘记填写表单重置</p>
    <form method="post" action="/forgetpwd/" autocomplete="off">
        <input name="email" value="{% if forgetpwd_form.email.value %}{{ forgetpwd_form.email.value }}{% endif %}" type="email" class="form-control" placeholder="请输入注册时的邮箱" required="">
        {% if forgetpwd_form.errors.email %}
            <span class="help-block m-b-none"> {{ forgetpwd_form.errors.email.as_text }}</span>
        {% endif %}
    
        <div class="input-group">
            <input type="text" name="captcha_1" required="" id="id_captcha_1" class="form-control" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false" style="width: 75%" placeholder="验证码">
            <img  style="width: 25%; float: left; margin-top: 15px;height: 30px" src="{{ image_url }}" alt="captcha" class="captcha">
            <input type="hidden" name="captcha_0" value="{{ hashkey }}" required="" id="id_captcha_0">
        </div>
    
        {# register_form.captcha #} <!-- 可以使用register_form表单自动生成表单框和验证码图片 -->
        {#【{{ image_url }}、{{ hashkey }}】#}
    
        {% if forgetpwd_form.errors.captcha %}
            <span class="help-block m-b-none"> {{ forgetpwd_form.errors.captcha.as_text }}</span>
        {% endif %}
    
        {% csrf_token %}
    
        {% if msg %}
            <br>
            <div class="alert alert-danger" style="padding: 5px;">
                {{ msg }}
            </div>
        {% endif %}
    
        <button type="submit" class="btn btn-primary block full-width m-b">发 送</button>
    
        <p class="text-muted text-center"><small>想起来了?</small><a href="/login/">点此登录</a>
        </p>
    </form>
    
    
        <script src="{% static 'js/jquery.min.js' %}"></script>
    
        <script>
            $('.captcha').click(function () {
            $.getJSON("/captcha/refresh/", function (result) {
                $('.captcha').attr('src', result['image_url']);
                $('#id_captcha_0').val(result['key'])
            });
        });
        </script>
    

    BLOG_20190604_135509_57

    忘记密码表单ForgetPwdForm(forms.Form)

    # 忘记密码表单
    class ForgetPwdForm(forms.Form):
        email = forms.EmailField(required=True)
        captcha = CaptchaField(error_messages={'invalid': '验证码错误'})
    

    忘记密码视图ForgetPwdView(View)

    from .forms import LoginForm, RegisterForm, ForgetPwdForm
    
    
    # 忘记密码视图
    class ForgetPwdView(View):
        def get(self, request):
            forgetpwd_form = ForgetPwdForm()
            # 图片验证码
            hashkey = CaptchaStore.generate_key()
            image_url = captcha_image_url(hashkey)
            return render(request, 'forgetpwd.html',
                          {
                              'forgetpwd_form': forgetpwd_form,
                              'hashkey': hashkey,
                              'image_url': image_url,
                          })
    

    忘记密码url

    from users.views import user_login, LoginView, RegisterView, ActiveUserView, ForgetPwdView
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('xadmin/', xadmin.site.urls),
        path('', TemplateView.as_view(template_name='index.html'), name='index'),
        # path('login/', TemplateView.as_view(template_name='login.html'), name='login'),
        # path('login/', user_login, name='login'),
        path('login/', LoginView.as_view(), name='login'),  # 基于类方法实现登录,这里是调用它的方法
        path('register/', RegisterView.as_view(), name='register'),
        re_path('register/active/(?P<active_code>.*)/', ActiveUserView.as_view(), name='user_active'),  # 激活
        path('captcha/', include('captcha.urls')),
        path('forgetpwd/', ForgetPwdView.as_view(), name='forgetpwd'),  # 忘记密码
    ]
    

    忘记密码post逻辑ForgetPwdView(View)

    发送邮件模块email_send.py增加忘记密码操作

    # 发送注册邮件
    def send_register_email(request_uri, email, send_type='register'):
        # 发送之前先保存到数据库,到时候查询链接是否存在
    
        # 实例化一个EmailVerifyRecord对象
        email_record = EmailVerifyRecord()
        # 生成随机的code放入链接
        code = random_str(16)
    
        email_record.code = code
        email_record.email = email
        email_record.send_type = send_type
    
        email_record.save()
    
        # 定义邮件内容
        email_title = ''
        email_body = ''
    
        if send_type == 'register':
            email_title = '在线学习平台 注册激活链接'
            email_body = '请点击链接激活账号:{}active/{}'.format(request_uri, code)  # request_uri='http://127.0.0.1:8000/register/'
    
            # 使用Django内置函数完成邮件发送。四个参数:主题,邮件内容,从哪里发,接受者list
            send_status = send_mail(email_title, email_body, settings.EMAIL_FROM, [email])
            if send_status:
                return True
            else:
                return False
    
        elif send_type == 'forget':
            email_title = '在线学习平台 密码重置链接'
            email_body = '请点击链接重置密码:{}reset/{}'.format(request_uri, code)  # request_uri='http://127.0.0.1:8000/forgetpwd/'
    
            # 使用Django内置函数完成邮件发送。四个参数:主题,邮件内容,从哪里发,接受者list
            send_status = send_mail(email_title, email_body, settings.EMAIL_FROM, [email])
            if send_status:
                return True
            else:
                return False
    

    忘记密码增加发送邮件功能

    # 忘记密码视图
    class ForgetPwdView(View):
        def get(self, request):
            # print(request.build_absolute_uri())
            forgetpwd_form = ForgetPwdForm()
            # 图片验证码
            hashkey = CaptchaStore.generate_key()
            image_url = captcha_image_url(hashkey)
            return render(request, 'forgetpwd.html',
                          {
                              'forgetpwd_form': forgetpwd_form,
                              'hashkey': hashkey,
                              'image_url': image_url,
                          })
    
        def post(self, request):
            forgetpwd_form = ForgetPwdForm(request.POST)
            # 图片验证码
            hashkey = CaptchaStore.generate_key()
            image_url = captcha_image_url(hashkey)
    
            if forgetpwd_form.is_valid():
                email = request.POST.get('email', '')
                if UserProfile.objects.filter(email=email):
                    # 如果邮箱是注册过的,就发送改密邮件,然后跳回登录页面
                    send_register_email(request_uri=request.build_absolute_uri(), email=email, send_type='forget')
    
                    return render(request, 'login.html',
                                  {
                                      'msg': '重置密码邮件已发送,请注意查收',
                                  })
                else:
                    return render(request, 'forgetpwd.html',
                                  {
                                      'forgetpwd_form': forgetpwd_form,
                                      'hashkey': hashkey,
                                      'image_url': image_url,
                                      'msg': '邮箱未注册,请检查是否输入错误'
                                  })
            else:
                return render(request, 'forgetpwd.html',
                              {
                                  'forgetpwd_form': forgetpwd_form,
                                  'hashkey': hashkey,
                                  'image_url': image_url,
                              })
    

    重置密码

    收到重置密码链接

    请点击链接重置密码:http://127.0.0.1:8000/forgetpwd/reset/bP6hGgtU4DUN8lnd
    

    跳转密码修改url

    from users.views import user_login, LoginView, RegisterView, ActiveUserView, ForgetPwdView, RestpwdView
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('xadmin/', xadmin.site.urls),
        path('', TemplateView.as_view(template_name='index.html'), name='index'),
        # path('login/', TemplateView.as_view(template_name='login.html'), name='login'),
        # path('login/', user_login, name='login'),
        path('login/', LoginView.as_view(), name='login'),  # 基于类方法实现登录,这里是调用它的方法
        path('register/', RegisterView.as_view(), name='register'),
        re_path('register/active/(?P<active_code>.*)/', ActiveUserView.as_view(), name='user_active'),  # 激活
        path('captcha/', include('captcha.urls')),
        path('forgetpwd/', ForgetPwdView.as_view(), name='forgetpwd'),  # 忘记密码
        re_path('forgetpwd/reset/(?P<active_code>.*)/', RestpwdView.as_view(), name='resetpwd'),  # 密码重置验证
    ]
    

    跳转密码修改表单RestpwdView(View)

    点击上面的,这个视图验证后跳转到,如果验证通过,返回密码修改表单

    # 重置密码
    class RestpwdView(View):
        def get(self, request, active_code):
            # 查询验证码是否存在
            all_record = EmailVerifyRecord.objects.filter(code=active_code)
    
            if all_record:
                for record in all_record:
                    email = record.email
    
                    return render(request, 'pwdreset.html',
                                  {
                                      'email': email
                                  })
            else:
                forgetpwd_form = ForgetPwdForm()
                hashkey = CaptchaStore.generate_key()
                image_url = captcha_image_url(hashkey)
    
                return render(request, 'forgetpwd.html',
                              {
                                  'forgetpwd_form': forgetpwd_form,
                                  "msg": "您的重置链接无效",
                                  'hashkey': hashkey,
                                  'image_url': image_url,
                              })
    

    密码修改模板pwdreset.html

    <h3 class="no-margins">重置修改</h3>
    <p class="m-t-md">密码重置修改</p>
    <form method="post" action="{% url 'modify_pwd' %}" autocomplete="off">
        <input name='email' type="text" value="{{ email }}" hidden />
    
        <input name='password' type="password" class="form-control pword m-b" placeholder="密码" />
        {% if modifypwd_form.errors.password %}
            <span class="help-block m-b-none"> {{ modifypwd_forms.errors.password.as_text }}</span>
        {% endif %}
        <input name='re_password' type="password" class="form-control pword m-b" placeholder="重复密码" />
        {% if modifypwd_form.errors.re_password %}
            <span class="help-block m-b-none"> {{ modifypwd_form.errors.re_password.as_text }}</span>
        {% endif %}
    
        {% if msg %}
            <div class="alert alert-danger" style="padding: 5px;">
                {{ msg }}
            </div>
        {% endif %}
    
        {% csrf_token %}
    
        <a href="/login/">返回登录</a>
        <button type="submit" class="btn btn-success btn-block">修 改</button>
    </form>
    

    密码修改表单ModifyPwdForm(forms.Form)

    # 重置密码form实现
    class ModifyPwdForm(forms.Form):
        # 密码不能小于5位
        password1 = forms.CharField(required=True, min_length=5)
        # 密码不能小于5位
        password2 = forms.CharField(required=True, min_length=5)
    

    密码修改视图

    from .forms import LoginForm, RegisterForm, ForgetPwdForm, ModifyPwdForm
    
    
    # 修改密码
    class ModifypwdView(View):
        def post(self, request):
            modifypwd_form = ModifyPwdForm(request.POST)
    
            if modifypwd_form.is_valid():
                pwd1 = request.POST.get("password", "")
                pwd2 = request.POST.get("re_password", "")
                email = request.POST.get("email", "")
                # 如果两次密码不相等,返回错误信息
                if pwd1 != pwd2:
                    return render(request, "pwdreset.html",
                                  {
                                      "email": email,
                                      "msg": "密码不一致",
                                      'modifypwd_form': modifypwd_form,
                                   })
                # 如果密码一致
                user = UserProfile.objects.get(email=email)
                # 加密成密文
                user.password = make_password(pwd2)
                # save保存到数据库
                user.save()
                return render(request, "login.html", {"msg": "密码修改成功,请登录"})
            else:
                email = request.POST.get("email", "")
                return render(request, 'pwdreset.html',
                              {
                                  'email': email,
                                  'modifypwd_form': modifypwd_form,
                              })
    

    密码修改url

    from users.views import user_login, LoginView, RegisterView, ActiveUserView, ForgetPwdView, RestpwdView, ModifypwdView
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('xadmin/', xadmin.site.urls),
        path('', TemplateView.as_view(template_name='index.html'), name='index'),
        # path('login/', TemplateView.as_view(template_name='login.html'), name='login'),
        # path('login/', user_login, name='login'),
        path('login/', LoginView.as_view(), name='login'),  # 基于类方法实现登录,这里是调用它的方法
        path('register/', RegisterView.as_view(), name='register'),
        re_path('register/active/(?P<active_code>.*)/', ActiveUserView.as_view(), name='user_active'),  # 激活
        path('captcha/', include('captcha.urls')),
        path('forgetpwd/', ForgetPwdView.as_view(), name='forgetpwd'),  # 忘记密码
        re_path('forgetpwd/reset/(?P<active_code>.*)/', RestpwdView.as_view(), name='resetpwd'),  # 密码重置验证
        path('modify_pwd/', ModifypwdView.as_view(), name="modify_pwd"),  # 密码修改
    ]
    

    相关文章

      网友评论

        本文标题:【Django在线教育平台】06.找回密码,实现忘记密码及重置密

        本文链接:https://www.haomeiwen.com/subject/ecglxctx.html