實現方法:
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中創造這些路徑