实战django(二)--登录实现记住我
上节初步实现了登录和注册模块,这节我们进一步实现“记住我”功能。
大体功能分为以下模块:
1.在登录时如果勾选记住我,那么就将用户username存进cookie中,跳转到index页面;
2.此时,如果不进行登出,如果直接返回登录页面,那么就会判断cookie中是否存在username,如果存在,就直接跳转到Index界面,也就是不用再一次登录;
3.如果进行登出,则删除cookie中的username,并返回登录界面;
4.如果登录时不勾选记住我,那么跳转到index界面后,在访问登录界面不会继续跳转到Index界面;
5.若直接访问Index界面,会判断cookie中是否存在username,如果不存在,则会提示对不起,请先登录,三秒之后跳转到登录界面。
urls.py
from django.urls import path from . import views app_name='login' urlpatterns=[ path('',views.login,name='login'), path('register/',views.register,name='register'), path('register/savereg/',views.save_register,name='savereg'), path('tologin/',views.to_login,name='tologin'), path('logout/',views.logout,name='logout'), path('index/',views.index,name='index'), ]
views.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.shortcuts import render, redirect from .models import Users import datetime # Create your views here. def login(request): if request.get_signed_cookie('username', salt='SSS', default=None) != None: username = request.get_signed_cookie('username', salt='SSS', default=None) return render(request, 'login/index.html', {'username': username}) return render(request,'login/login.html') def register(request): return render(request,'login/register.html') def save_register(request): if request.method == 'POST': phone=request.POST.get('phone') username=request.POST.get('username') password=request.POST.get('password') repassword=request.POST.get('repassword') birthday=request.POST.get('birthday') errormsg='' if phone =='': errormsg='手机号不能为空' elif password =='': errormsg='密码不能为空' else: if password!=repassword: errormsg='确认密码与密码不一致' if errormsg == '': Users.objects.create(phone=phone,username=username,password=password,birthday=birthday, regday=datetime.datetime.now().strftime('%Y-%m-%d')) return render(request,'login/pagejump.html') else: return render(request,'login/register.html',context={'errormsg':errormsg}) def to_login(request): if request.method == 'POST': phone=request.POST.get('phone') remember=request.POST.get('remember') if phone == '': return render(request, 'login/login.html', {'errormsg': '用户名不能为空'}) try: user_obj = Users.objects.get(phone=phone) except Users.DoesNotExist: return render(request,'login/login.html',{'errormsg':'账号不存在,请重新输入'}) pwd=user_obj.password password = request.POST.get('password') if password != '': repwd=password if pwd == repwd: username=user_obj.username if remember is not None: response = render(request, 'login/index.html',{'username':username}) response.set_signed_cookie("username", username, salt="SSS", max_age=60 * 60 * 12) return response else: return render(request, 'login/index.html', {'username': username}) # return render(request, 'login/index.html',{'username':username}) else: return render(request, 'login/login.html',{'errormsg':'密码错误'}) else: return render(request, 'login/login.html', {'errormsg': '密码不能为空'}) def check_login(func): def helper(request,*args,**kwargs): if request.get_signed_cookie('username',salt='SSS',default=None) != None: return func(request,*args,**kwargs) else: return render(request,'login/checklogin.html') return helper def logout(request): response = redirect("/login/") response.delete_cookie("username") return response @check_login def index(request): return render(request,'login/index.html')
index.html
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h3><p>hello {{username}}</p></h3><span><p><a href="{% url 'login:logout'%}">登出</a></p></span> </body> </html>
login.html
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>盒老师</title> <meta name="keywords" content="盒老师"> <meta name="content" content="盒老师"> <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1"> <link type="text/css" rel="stylesheet" href="/static/login/css/login.css"> <script type="text/javascript" src="/static/login/js/jquery.min.js"></script> </head> <body class="login_bj" > <div class="zhuce_body" style="position:absolute;left:130px;top:300px;"> <div class="zhuce_kong login_kuang" > <div class="zc"> <div class="bj_bai" style="height:330px;"> <h3>登录</h3> <form action="{% url 'login:tologin'%}" method="post"> <p style="color: red;margin-top: 0px;">{{errormsg}}</p> <input name="phone" type="text" class="kuang_txt" placeholder="手机号"> <input name="password" type="text" class="kuang_txt" placeholder="密码"> <div> <input name="remember" type="checkbox" value="remember" ><span>记住我</span><a href="#" style="float:rigth;">忘记密码</a> </div> <div> <p>没有账号?<a href="{% url 'login:register'%}">立即注册</a></p> </div> <input style="margin-top:2px;" name="登录" type="submit" class="btn_zhuce" value="登录"> </form> </div> </div> </div> </div> </body> </html>
checklogin.html
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<body> <div align="center" style="border: 1px solid blueviolet; position:absolute;left:500px;top: 200px;width: 430px;height: 50px;"> <p style="text-align: center;font-size: 20px;">对不起!请先登录!还有<span id="sp">3</span>秒跳转到登录界面...</p> </div> <script> //onload事件会在页面加载完后立即发生 onload=function () { //etInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。 setInterval(go,1000) }; var x=2; function go() { if (x>=0){ document.getElementById("sp").innerText=x; }else { location.href="{% url 'login:login'%}"; } x--; } </script> </body>
到这里,登录注册也基本告一段落了。同时我的django之旅也暂时告一段落了,花了接近一个月的时间,也算是有所收获,找时间会将所有代码上传至github。接下来准备去看自然语言处理了,极大可能是自己以后工作的内容。