创建templates/login.htm
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/student/login/" method="post">
{% csrf_token %}
<p>
<label>用户名:</label><input type="text" name="sname" value="{{ sname }}">
</p>
<p>
<label>密码:</label><input type="password" name="pwd" value="{{ pwd }}">
</p>
<p>
<input type="checkbox" name="check" value="1">记住密码
</p>
<p>
<input type="submit" value="登录">
</p>
</form>
</body>
</html>
配置路由
根路由
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('student/',include('stu.urls'))
]
子路由
#coding=utf-8
from django.conf.urls import url
from stu import views
urlpatterns = [
url('^login/$',views.index_login)
]
创建视图函数
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def index_login(request):
if request.method == 'GET':
# 判断request中是否存在'login'对应cookie信息
if 'login' in request.COOKIES:
login = request.COOKIES.get('login','').split(',')
sname = login[0]
pwd = login[1]
return render(request,'login.html',{'sname':sname,'pwd':pwd})
return render(request,'login.html')
else:
# 获取请求参数
sname = request.POST.get('sname','')
pwd = request.POST.get('pwd','')
flag = request.POST.get('check','')
response = HttpResponse()
# 判断是否登录成功
if sname == 'lisi' and pwd == '123':
response.content = '登陆成功'
# 判断是否需要记住密码
if flag:
# 将用户名和密码存放至cookie中
response.set_cookie('login',sname+','+pwd,max_age=3*24*60*60,
path='/student/login/')
else:
# 当不需要记住密码时,需要删除cookie中‘login’对应的数据
response.delete_cookie('login',path='/student/login/')
else:
response.delete_cookie('login', path='/student/login/')
#重定向
response.status_code = 302
response.setdefault('Location','/student/login/')
return response