1. 忘记密码页面展示
1.在users.views.py文件中定义视图
from django.views import Viewclass ForgetPasswordView(View):def get(self, request):return render(request, 'forget_password.html')
2.在users.urls.py文件中定义路由
from users.views import ForgetPasswordViewurlpatterns = [# 参数1:路由# 参数2:视图函数# 参数3:路由名,方便通过reverse来获取路由path('forgetpassword/', ForgetPasswordView.as_view(),name='forgetpassword'),]
3.修改forget_password.html中的资源加载方式
<!-- Header部分 -->{% load staticfiles %}<!-- 引入bootstrap的css文件 --><link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}"><!-- 引入vuejs --><script type="text/javascript" src="{% static 'js/vue-2.5.16.js' %}"></script><script type="text/javascript" src="{% static 'js/axios-0.18.0.min.js' %}"></script>...<!-- Footer部分 --><script type="text/javascript" src="{% static 'js/host.js' %}"></script><script type="text/javascript" src="{% static 'js/common.js' %}"></script><script type="text/javascript" src="{% static 'js/forget_password.js' %}"></script>...<!-- 图片验证码部分 --><img :src="image_code_url" @click="generate_image_code" alt="" style="width: 110px;height: 40px;">
4.修改login.html中的忘记密码的跳转连接
<small class="form-text text-muted ml-1"><a class="secondaryAction layui-text" href="{% url 'users:forgetpassword' %}">忘记密码?</a>
2. 忘记密码接口设计
1.请求方式
2.请求参数:表单
3.响应结果:HTML
3. 忘记密码接口实现
class ForgetPasswordView(View):def post(self, request):# 接收参数mobile = request.POST.get('mobile')password = request.POST.get('password')password2 = request.POST.get('password2')smscode = request.POST.get('sms_code')# 判断参数是否齐全if not all([mobile, password, password2, smscode]):return HttpResponseBadRequest('缺少必传参数')# 判断手机号是否合法if not re.match(r'^1[3-9]\d{9}$', mobile):return HttpResponseBadRequest('请输入正确的手机号码')# 判断密码是否是8-20个数字if not re.match(r'^[0-9A-Za-z]{8,20}$', password):return HttpResponseBadRequest('请输入8-20位的密码')# 判断两次密码是否一致if password != password2:return HttpResponseBadRequest('两次输入的密码不一致')# 验证短信验证码redis_conn = get_redis_connection('default')sms_code_server = redis_conn.get('sms:%s' % mobile)if sms_code_server is None:return HttpResponseBadRequest('短信验证码已过期')if smscode != sms_code_server.decode():return HttpResponseBadRequest('短信验证码错误')# 根据手机号查询数据try:user = User.objects.get(mobile=mobile)except User.DoesNotExist:# 如果该手机号不存在,则注册个新用户try:User.objects.create_user(username=mobile, mobile=mobile, password=password)except Exception:return HttpResponseBadRequest('修改失败,请稍后再试')else:# 修改用户密码user.set_password(password)user.save()# 跳转到登录页面response = redirect(reverse('users:login'))return response
运行效果: