本文实例讲述了django框架实现的普通登录。分享给大家供大家参考,具体如下:
1.显示登录页面
a.设计url,通过浏览器访问http://127.0.0.1:8000//login的时候现实登录页面
b.设计url对应的视图函数
c.编写模板文件login.html
2.登录校验功能
校验数据库中有没有这个用户,这里用模拟的伪校验
新建login.html
在templates文件夹下的booktest文件夹下新建
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<!doctype html>
<html lang = "en" >
<head>
<meta charset = "utf-8" >
<title>title< / title>
< / head>
<body>
post:提交的参数在请求头里,数据比较重要用post
get:提交的参数在url中
用post方法提交到login_check页面中
<form method = "post" action = "/login_check" >
用户名:< input type = "text" name = "username" >
密码:< input type = "password" name = "password" >
< input type = "submit" value = "登录" >
< / form>
< / body>
< / html>
|
注意这里表单的提交方法选择post方法,action配置如上
配置urls.py
1
2
|
url(r '^login$' ,views.login),
url(r '^login_check$' ,views.login_check),
|
views.py写视图函数login()
和login_check()
login函数直接现实登录页面,login_check函数用request.post.get()
函数接受浏览器传递过来的参数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
def login(request):
'''显示登录页面'''
return render(request, 'booktest/login.html' )
def login_check(request):
'''登录校验视图'''
# 浏览器提交的信息就保存在request里面
# request.post保存的是post提交的参数
# request.get保存的是get提交的参数
# 1.获取提交的用户名和密码
username = request.post.get( 'username' )
passwoed = request.post.get( 'password' )
# 2.进行登录校验
# 实际开发的时候,用户名和密码保存在数据库中
# 模拟
if username = = 'zhangyue' and passwoed = = '123456' :
# 正确,跳转到首页index
return redirect( '/index' )
else :
# 错误
return redirect( '/login' )
# 3.返回应答
|
发生forbidden (403)错误
去项目的setting.py里注释掉
'django.middleware.csrf.csrfviewmiddleware',
希望本文所述对大家基于django框架的python程序设计有所帮助。
原文链接:https://blog.csdn.net/qq_34788903/article/details/87896645