python_Django 實現登入功能form表單的引數接收處理
阿新 • • 發佈:2018-12-22
1.建立Django工程。
參考https://www.cnblogs.com/CK85/p/10159159.html中步驟。
2.在urls.py檔案中新增url分發路徑
"""Django_test URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('login/', views.login, name='login'), path('authentication/', views.authentication, name='authentication'), ]
路徑分發時編輯name可以為路徑取一個別名,在html檔案中通過別名進行訪問,避免過多的命名的改變。
3.在view.py中新增兩個介面的試圖函式。
from django.shortcuts import render, HttpResponse import time # Create your views here. def login(request): return render(request, 'login.html', locals()) def authentication(request): # print(request.method) user_name = request.GET.get('user') pwd = request.GET.get('pwd') user_dic = { 'ck': '123', 'ck1': '123', 'ck2': '123', } if user_name in user_dic: if user_dic[user_name] == pwd: print('authentication passed') user = user_name output = render(request, 'well_come.html', {'username': user}) else: print('incorrect username or password') output = HttpResponse('<h1>incorrect username or password</h1>') else: print('不在') output = HttpResponse('<h1>the user dose not exist</h1>') return output
login檢視函式在使用者訪問時將login.html傳送給使用者。
authentication進行使用者登入資訊的驗證和處理。
HttpResponse返回一個http響應。
4.在templates資料夾中建立對應的html檔案:
login.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>登入</h1> <div> <form action="{% url "authentication" %}" > <p>手機號:<input type="text" name="user"></p> <p>密碼:<input type="text" name="pwd"></p> <p><input type="submit" value="提交"></p> {% csrf_token %} </form> </div> </body> </html>
login介面是使用者在登入時看到的介面,需要使用者在該頁面中輸入賬號和密碼。
其中使用form表單進行讀取資料,action=“/authentication/”與action=“{% url "authentiction" %}”相同,前者使用路徑訪問,後者使用別名訪問。
在form表單中input標籤type=’text‘ 和type=’submit‘組合使用,使得在使用者點選提交按鈕時使用form表單method中傳入的方法將兩個text中的值與text的name組成鍵值對傳給在form表單action路徑的檔案。
well_come.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>你好! {{ username }}</h1> </body> </html>
well_come介面為使用者成功登入之後的歡迎介面。