码迷,mamicode.com
首页 > 其他好文 > 详细

在线教育平台,找回密码(10)

时间:2020-05-23 00:07:10      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:a20   return   sub   mod   method   form表单   end   设置   ace   

路由:

from users.views import ForgetPwdView

urlpatterns = [
    path(forget/,ForgetPwdView.as_view(),name=forget_pwd),
]

表单forms.py

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

视图函数

class ForgetPwdView(View):
    ‘‘‘找回密码‘‘‘
    def get(self,request):
        forget_form = ForgetPwdForm()
        return render(request,‘forgetpwd.html‘,{‘forget_form‘:forget_form})

    def post(self,request):
        forget_form = ForgetPwdForm(request.POST)
        if forget_form.is_valid():
            email = request.POST.get(‘email‘,None)
            send_register_eamil(email,‘forget‘)
            return render(request, ‘send_success.html‘)
        else:
            return render(request,‘forgetpwd.html‘,{‘forget_form‘:forget_form})

修改login.html中的url

<a class="fr" href="{% url ‘forget_pwd‘ %}">忘记密码?</a>

把forgetpwd.html拷贝到templates文件下

修改静态文件路径

显示验证码

 <div class="form-group captcha1 marb38">
     <label>验&nbsp;证&nbsp;码</label>
     {{ forget_pwd.captcha }}
</div>

发送找回邮件

# apps/utils/email_send.py

from random import Random
from django.core.mail import send_mail

from users.models import EmailVerifyRecord
from MxOnline.settings import EMAIL_FROM

# 生成随机字符串
def random_str(random_length=8):
    str = ‘‘
    # 生成字符串的可选字符串
    chars = AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789
    length = len(chars) - 1
    random = Random()
    for i in range(random_length):
        str += chars[random.randint(0, length)]
    return str

# 发送注册邮件
def send_register_eamil(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 = "NBA注册激活链接"
        email_body = "请点击下面的链接激活你的账号: http://127.0.0.1:8000/active/{0}".format(code)

        # 使用Django内置函数完成邮件发送。四个参数:主题,邮件内容,从哪里发,接受者list
        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        # 如果发送成功
        if send_status:
            pass

    if send_type == "forget":
        email_title = "NBA找回密码链接"
        email_body = "请点击下面的链接找回你的密码: http://127.0.0.1:8000/reset/{0}".format(code)

        # 使用Django内置函数完成邮件发送。四个参数:主题,邮件内容,从哪里发,接受者list
        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        # 如果发送成功
        if send_status:
            pass

email_send.py

新建templates/send_success.html

技术图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>邮件已发送,请注意查收</p>
</body>
</html>

修改forgetpwd.html

技术图片
<form id="jsFindPwdForm" method="post" action="{% url ‘forget_pwd‘ %}" autocomplete="off">
                    <input type=hidden name=csrfmiddlewaretoken value=mymQDzHWl2REXIfPMg2mJaLqDfaS1sD5/>
                    <div class="form-group marb20 {% if forget_from.errors.email %}errorput{% endif %}">
                        <label>帐     号</label>
                        <input type="text" id="account" name="email" value="{{ forget_from.email.value }}"
                               placeholder="邮箱"/>
                    </div>
                    <div class="form-group captcha1 marb38 {% if forget_from.errors.captchal %}errorput{% endif %}">
                        <label>验 证 码</label>
                        {{ forget_form.captcha }}
                    </div>
                    <div class="error btns" id="jsForgetTips">
                        {% for key,error in forget_from.errors.items %}
                            {{ error }}
                        {% endfor %}
                        {{ msg }}
                    </div>
                    <input type="hidden" name="sms_type" value="1">
                    <input class="btn btn-green" id="jsFindPwdBtn" type="submit" value="提交"/>
                    <p class="form-p" style="bottom:40px;">您还可以<a href="login.html"> [直接登录]</a></p>
                    <input type=hidden name=csrfmiddlewaretoken value=5I2SlleZJOMUX9QbwYLUIAOshdrdpRcy/>
                    {% csrf_token %}
                </form>
View Code

 

重置密码:

(1)重置密码激活邮箱的url

 re_path(‘reset/(?P<active_code>.*)/‘, ResetView.as_view(), name=‘reset_pwd‘),

(2)写重置密码(get方式)后台逻辑

技术图片
class ResetView(View):
    def get(self, request, active_code):
        all_records = EmailVerifyRecord.objects.filter(code=active_code)
        if all_records:
            for record in all_records:
                email = record.email
                return render(request, "password_reset.html", {"email":email})
        else:
            return render(request, "active_fail.html")
        return render(request, "login.html")
技术图片

(3)创建修改密码的form表单

class ModifyPwdForm(forms.Form):
    ‘‘‘重置密码‘‘‘
    password1 = forms.CharField(required=True, min_length=5)
    password2 = forms.CharField(required=True, min_length=5)

(4)修改密码的url

上面那个是激活邮箱的url,有active_code参数,只能写get方式的逻辑。

这里必须单独新建一个修改密码的url,因为如果以post方式提交的话,post提交的地方跟get方式(url中需要active_code参数)的地址不一样,action="{% url ‘modify_pwd‘ %}

path(‘modify_pwd/‘, ModifyPwdView.as_view(), name=‘modify_pwd‘),

(5)修改密码的后台逻辑

技术图片
class ModifyPwdView(View):
    def post(self, request):
        modify_form = ModifyPwdForm(request.POST)
        if modify_form.is_valid():
            pwd1 = request.POST.get("password1", "")
            pwd2 = request.POST.get("password2", "")
            email = request.POST.get("email", "")
            if pwd1 != pwd2:
                return render(request, "password_reset.html", {"email":email, "msg":"密码不一致!"})
            user = UserProfile.objects.get(email=email)
            user.password = make_password(pwd2)
            user.save()

            return render(request, "login.html")
        else:
            email = request.POST.get("email", "")
            return render(request, "password_reset.html", {"email":email, "modify_form":modify_form })

 

(6)修改password_reset.html

技术图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <title>密码修改</title>
    <link rel="stylesheet" type="text/css" href="/static/css/reset.css">
    <link rel="stylesheet" type="text/css" href="/static/css/animate.css">
    <link rel="stylesheet" type="text/css" href="/static/css/style.css">

<body>
<div class="wp">
    <div class="resetpassword" id="resetPwdForm">
        <h1>修改密码</h1>
        <p>已经通过验证,请设置新密码</p>
        <form id="reset_password_form" action="{% url ‘modify_pwd‘ %}" method="post">
            <ul>
                <li class="{% if modify_form.errors.password1 %}errorput{% endif %}">
                    <span class="">新 密 码 :</span>
                    <input type="password" name="password1" id="pwd" placeholder="6-20位非中文字符">
                    <i></i>
                </li>
                <input type="hidden" name="email" value="{{ email }}">
                <li class="{% if modify_form.errors.password2 %}errorput{% endif %}">
                    <span class="">确定密码:</span>
                    <input type="password" name="password2" id="repwd" placeholder="6-20位非中文字符">
                    <i></i>
                </li>
                <div class="error btns" id="jsPasswdResetTips">
                    {% for key,error in modify_form.errors.items %}{{ key }}:{{ error }}{% endfor %}{{ msg }}</div>
                <li class="button">
                    <input type="submit" value="提交">
                </li>
            </ul>
            {% csrf_token %}
        </form>
    </div>
    <div class="resetpassword" id="reset_password_tips" style="display:none;">
        <h1>修改密码成功,请重新登录</h1>
        <img class="fl" src="/static/images/check2.png">
        <p class="successword">已经成功修改密码,请重新登录</p>
    </div>
</div>
</body>
</html>

san

 

在线教育平台,找回密码(10)

标签:a20   return   sub   mod   method   form表单   end   设置   ace   

原文地址:https://www.cnblogs.com/topass123/p/12940321.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!