实现方法:1,可以先定义一个基础的页面访问路径 例如:http://127.0.0.1:8000/index/ 定义index路径
在urls
1 urlpatterns = [
2
3 url(r'^index/$', views.index),
4
5 ]
2,同时也需要创造一个index.html页面
<html xmlns="http://www.w3.org/1999/html">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<title>登陆页面</title>
</head>
<body>
<form method="post" action="/login_action/"> <!--创造一个表单,用于数据提交,并且使用post方式提交表单,同时定义为login_action(登陆)过程-->
<input name="username" type="text" placeholder="用户名"><br> <!--input标签定义文本框,数据类型-->
<input name="password" type="password" placeholder="密码"><br>
{{error}}<br> <!--这里的双大括号可以用于显示函数所指定的内容-->
<button id="btn" type="submit">登陆</button>
{% csrf_token %} <!--为了防止csrf攻击-->
</form>
</body>
</html>
3,需要一个将url和html连接起来的函数
定义views.py
1 from django.shortcuts import render
2 from django.http import HttpResponse
3 from django.http import HttpResponseRedirect #这三个模块为常用模块
4 # Create your views here.
5
6 def index(request):
7 return render(request, 'index.html')
8 def login_action(request):
9 if request.method == 'POST': #判断是否为post提交方式
10 username = request.POST.get('username', '') #通过post.get()方法获取输入的用户名及密码
11 password =request.POST.get('password', '')
12
13 if username == 'admin' and password == '123': #判断用户名及密码是否正确
14 return HttpResponseRedirect('/event_manage/') #如果正确,(这里调用另一个函数,实现登陆成功页面独立,使用HttpResponseRedirect()方法实现
15 else:
16 return render(request,'index.html',{'error':'username or password eror'})#不正确,通过render(request,"index.html")方法在error标签处显示错误提示
17
18 def event_manage(request): #该函数定义的是成功页面的提示页面
19
20 #username =request.COOKIES.get('user', '') #读取浏览器cookie
21 return render(request,"event_manage.html") #{"user":username}) #在上面的函数判断用户名密码正确后在显示该页面,指定到event_manage.html,切换到一个新的html页面
使用到的方法包括
render()
POST.get()
HttpResponseRedirect()HttpResponse()熟悉它们的使用
login_action()函数,对应index.html中定义的表单的提交过程,我们在这个过程中提交数据并且判断数据,
event_manage()函数用于打开新的html页面
5,创造成功页面event_manage.HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>成功</title>
</head>
<body>
<h1>你好,入侵者</h1>
</body>
</html>
在views.py 中定义的函数都应该在urls.py 中定义路径路径名称可以自定,但要与函数名称对应,这里为了与相应的功能对应
6,定义上面的两个函数的路径
urlpatterns = [
url(r'^index/$', views.index),
url(r'^login_action/$', views.login_action), #登陆过程
url(r'^event_manage/$', views.event_manage), #成功的页面
]
总结一下这整个流程
首先,我们通过http://127.0.0.1:8000/index/访问基础登陆页面
输入用户名密码,点击提交按钮,这一过程(login_action)调用login_action()函数{并且跳转到http://127.0.0.1:8000/login_action/}——————进行判断----------正确---------立马跳转到http://127.0.0.1:8000/event_manage/ ,并且显示event_manage.html.
整个实现过程
首先创造一个路径,相应的html页面
然后通过一个函数将他们捆绑到一起
实现表单内容提交的过程再定义一个函数用于处理数据,又定义一个函数,用于指定跳转到其它 的页面
总之,在views.py 中定义的是处理html中各种数据处理,数据判断,页面的跳转
同时定义的这些函数都是各个过程方法的链接,也应该在urls.py中创造这些路径

















