普通登录案例
1)显示登录页面
a)设计url,通过浏览器访问http://127.0.0.1:8000/login 时显示登录页面
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^index/$',views.index),
url(r'^login/$',views.login),
]
b)设计url对应视图函数login
def login(request):
'''显示登录页面'''
return render(request,'booktest/login.html')
c)编写模版文件login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<!--POST:提交的参数在请求集中 数据安全性要求比较高-->
<!--GET:提交的参数在url中-->
<form method="post" action="/login_check">
用户名:<input type="text" name="username"><br/>
密码:<input type="password" name="password"><br/>
<input type="submit" value="登录">
</form>
</body>
</html>
2)登录校验功能
a)设计url,点击登录页的登录按钮发起请求http://127.0.0.1:8000/login_check 进行登录校验
url(r'^login_check$',views.login_check)
b)设计url对应的视图函数,接收表单提交的数据,进行校验,若校验成功,则跳转成功页,若失败,则跳转登录页
def login_check(request):
'''登录校验视图'''
# 1、获取提交的用户名和密码
# request.POST 保存的是POST提交的参数 QueryDict
# request.GET 保存的是GET提交的参数
username = request.POST.get('username')
password = request.POST.get('password')
# 2、进行登录校验
# 实际开发:根据用户名和密码查找数据库
# 模拟:smart 123
if username == 'smart' and password == '123':
# 用户名密码正确,跳转首页
return redirect('/index')
else:
# 用户名密码错误,跳转登录页面
return redirect('/login')
c)校验成功,跳转首页
3)效果图
a)登录页面及登录失败页面

b)首页页面及登录成功页面

网友评论