此学习资料是通过虫师的python接口自动化出的书学习而来的,在此说明一下,想学习更多的自动化的同学可以找虫师的博客园,非广告,因为我python+selenium自动化也是跟虫师学的,学习效果很好的,特此推荐:
传送门
这里我们要进行开发一个发布会系统来了解Django框架,来看第二部分Django视图。
目录:
一、登录功能
二、Cookie和Session
三、Django认证系统
一、登录功能 返回目录
在上一章,我们已经简单用了html模板,在它基础上继续开发:
1、修改index.html文件为发布会html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Django Page</title>
</head>
<body>
<h1>发布会系统</h1>
<form>
<input name="username" type="text" placeholder="输入用户名"/>
<br/>
<input name="password" type="password" placeholder="输入密码"/>
<br/>
<button id="btn" type="submit">登录</button>
{% csrf_token %}
</form>
</body>
</html>
2、GET、POST请求
(1)GET请求
form标签中加入:method="get"
<form method="get">
<input name="username" type="text" placeholder="输入用户名"/>
<br/>
<input name="password" type="password" placeholder="输入密码"/>
<br/>
<button id="btn" type="submit">登录</button>
</form>
在页面输入用户名密码之后,提交表单,URL地址会添加用户名、密码
(2)POST请求
提交表单后,页面报错:
大概意思是Django对CSRF有保护措施,表单会自动生成令牌,通过令牌判断POST是否来自同一个网站,只需添加令牌即可,form添加{% csrf_token %}#}
<form method="post">
<input name="username" type="text" placeholder="输入用户名"/>
<br/>
<input name="password" type="password" placeholder="输入密码"/>
<br/>
<button id="btn" type="submit">登录</button>
# 添加令牌
{% csrf_token %}
</form>
再次刷新提交,就不报错了。
3、处理登录请求
修改index.html,添加action="/login_action/":
<form method="post" action="/login_action/">
再打开guest/urls.py文件,添加路径:
urlpatterns = [
...
url(r'^login_action/$', views.login_action)
]
再在sign/views.py下添加login_action()函数
def login_action(request):
if request.method == "POST":
username = request.POST.get("username","")
password = request.POST.get("password","")
if username == "" and password == "":
return HttpResponse("Django good!")
else:
return render(request,"index.html",{"error" : "Django login is error!"})
最后再在templates/index.html中添加error错误提示:
<form method="post" action="/login_action/">
<input name="username" type="text" placeholder="输入用户名"/>
<br/>
<input name="password" type="password" placeholder="输入密码"/>
<br/>
<button id="btn" type="submit">登录</button>
<br/>
# 提示信息
{{ error }}
{% csrf_token %}
</form>
{ { error } }:对应render返回字典中的key。
如果用户名密码正确则:
否则的话,提示报错信息:
4、登陆成功页面
但是,不能只是通过文字展示登录成功信息,必须需要替换为登录成功页面。
添加templates/enent_manage.html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Event Manage</title>
</head>
<body>
<h1>Login success!</h1>
</body>
</html>
修改sign/views.py
def login_action(request):
if request.method == "POST":
# "username"和"password"为name属性值,很重要
username = request.POST.get("username","")
password = request.POST.get("password","")
if username == "" and password == "":
# HttpResponseRedirect:这个类可以重定向指定页面
return HttpResponseRedirect("/event_manage/")
else:
return render(request,"index.html",{"error" : "Django login is error!"}) # 登陆成功页面
def event_action(request):
return render(request,"event_manage.html")
修改guest/urls.py:
urlpatterns = [
...
url(r'^event_manage/$', views.event_action),
]
再进行登录:
二、Cookie和Session 返回目录
1、Cookie的使用
首先修改sign/views.py:
def login_action(request):
if request.method == "POST":
username = request.POST.get("username","")
password = request.POST.get("password","")
if username == "" and password == "":
# 添加浏览器cookie
response = HttpResponseRedirect("/event_manage/")
# "user":cookie名;username获取登录用户名;3600cookie再浏览器保持时间
response.set_cookie("user",username,3600)
return response
else:
return render(request,"index.html",{"error" : "Django login is error!"}) def event_action(request):
# "user":读取cookie名
username = request.COOKIES.get("user","")
return render(request,"event_manage.html",{"cookie":username})
修改templates/event_manage.html:
<div style="float: left">
<a>欢迎{{ username }}到来!</a>
</div>
页面登录成功后:
通过谷歌浏览器查看Cookie信息:
2、Session的使用
但是考虑到安全问题,还是Session靠谱。
修改sign/views.py:
def login_action(request):
if request.method == "POST":
username = request.POST.get("username","")
password = request.POST.get("password","")
if username == "" and password == "":
# HttpResponseRedirect:这个类可以重定向指定页面
response = HttpResponseRedirect("/event_manage/")
# "user":cookie名;username获取登录用户名;3600cookie再浏览器保持时间
# response.set_cookie("user",username,3600) # 添加浏览器cookie
request.session["user"] = username # 将session信息记录到浏览器中
return response
else:
return render(request,"index.html",{"error" : "Django login is error!"}) def event_action(request):
# username = request.COOKIES.get("user","") # "user":读取cookie名
username = request.session.get("user","") #读取浏览器session
return render(request,"event_manage.html",{"username":username})
进行登录操作,但是报错:
提示:no such table: django_session,是因为session必须要有存储的地方才可以,我们需要创建django_session
再项目guest下,输入命令行:
# 输入命令
python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying sessions.0001_initial... OK
再进行登录,并查看session信息。
三、Django认证系统 返回目录
1、登录Admin后台
首先需要创建管理员账号,再终端输入:
test:guest zhan$ python manage.py createsuperuser
Username (leave blank to use 'zhan'): admin # 输入用户名
Email address: xxx@xxx.com # 输入邮箱
Password: # 输入密码
Password (again): # 再次输入密码
This password is too short. It must contain at least 8 characters. # 密码太短,并且不到8位
This password is too common. # 密码太简单
This password is entirely numeric. # 密码是数字
Password:
Password (again):
Error: Your passwords didn't match. # 密码不匹配
Password:
Password (again):
Superuser created successfully.
test:guest zhan$
登录网址:http://127.0.0.1:8000/admin/
输入用户名密码后登录:
2、引用Django认证登录
修改sign/views.py
def login_action(request):
if request.method == "POST":
username = request.POST.get("username","")
password = request.POST.get("password","")
# authenticate()函数接受用户名密码两个参数,并判断如果窜在返回user,不存在返回None
user = auth.authenticate(username=username,password=password)
if user != None:
auth.login(request,user) # 登录
# HttpResponseRedirect:这个类可以重定向指定页面
response = HttpResponseRedirect("/event_manage/")
request.session["user"] = username # 将session信息记录到浏览器中
return response
else:
return render(request,"index.html",{"error" : "Django login is error!"})
修改完成之后,通过跟后台系统用户名密码相关联,进行验证登录。
3、关上窗户
为什么要单独讲这一节呢,因为有一个现象时,直接登录成功页面:http://127.0.0.1:8000/event_manage/,发现直接就可以登录成功,但是这个往往是不行的,应该必须通过登录操作才可以进入登陆成功页面,所以我们只需要简单加个东西就好了。
修改sign/views.py:
from django.contrib.auth.decorators import login_required ...... # 限制
@login_required
def event_action(request):
username = request.session.get("user","") #读取浏览器session
return render(request,"event_manage.html",{"username":username})
只需要加入@login_required,即可。
注意:需要清理缓存。
但是,地址指向让它指向登录页面就更好啦。
修改guest/urls.py,增加新的路径:
urlpatterns = [
......
url(r'^$', views.index), # 8080地址也可以访问登录页面
......
url(r'^accounts/login/$', views.index), # 访问登陆成功页面,自动跳转登录页面
]
此时访问:
http://127.0.0.1:8000/
http://127.0.0.1:8000/index/
http://127.0.0.1:8000/event_manage/
都可以访问登录页面。