後臺實現簡單登陸總結
阿新 • • 發佈:2018-12-20
目錄
登陸頁面 temlates - login.html
<form action="" method="post"> <p>使用者名稱:<input type="text" name="name" class="form-control"></p> <p > 密碼:<input type="password" name="pwd" class="form-control"> </p> <input type="submit" value="提交">
總結:
- action -- 提交資料提交後臺的三種寫法 1、http://127.0.0.1:8000/login 2、/login/ ---- 推薦使用 3、空 ---- 預設使用當前頁面的路由傳輸,不推薦
- method -- 兩種提交請求方式 get:獲取頁面的資料,攜帶的資料往往是是不重要的,且資料的大小存在限制 post:提交資料的安全模式,不會講資料放置在url內
前端樣式 static - css、js、vue……
總結步驟:
- 手動建立一個static資料夾在根路徑下
- 可放入一些靜態檔案,前端樣式或者圖片等素材檔案
- 在setting內新增配置 STATIC_URL = '/static/'
- 在setting內新增配置(用來匹配第三部配置的路由,可以設定多條檔案路徑,查詢時會從上到下依次查詢)
STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), # os.path.join(BASE_DIR, 'static2'), ]
檢視層操作傳輸的資料 views.py
def login(request): if request.method == 'GET': return render(request, 'login.html') elif request.method == 'POST': print(request.POST) # name=request.POST.get('name') name = request.POST['name'] pwd = request.POST.get('pwd') user=models.User.objects.filter(name=name,pwd=pwd).first() if user: return redirect('http://www.baidu.com') else: return HttpResponse('使用者名稱密碼錯誤')
總結:
- request.method -- 判斷前臺提交過來的請求方式(GET 、POST)
- request.POST -- post 資料獲取,返回字典 request.POST [‘前臺標籤的name’] -- 類字典的使用方式(不推薦) request.POST.get('name') -- 推薦的指定取值方式,若同名取出同名的最後一個值 request.POST.getlist('name') -- 取出獲取的列表,存在同名的所有值
- from django.shortcuts import HttpResponse :資料從後臺返回前臺
- from django.shortcuts import render:模板從後臺返回前臺,使用路徑
render(reguest, 'books.html', {'book_list': dic})- from django.shortcuts import redirect:路徑的重定向,即頁面的跳轉
ORM(Object Relational Mapping,全稱物件關係對映)連線資料庫
操作資料庫總結:
- setting內進行default配置
'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '127.0.0.1', 'PORT': 3306, 'USER': 'root', 'PASSWORD': 'Apassword', 'NAME':'django',//資料庫名字 }
- app - __init__.py ------ 將預設的資料庫方式轉化為pymysql連線方式
import pymysql pymysql.install_as_MySQLdb()
- models,py內建立表結構
from django.db import models # 一個類就是一個表 class User(models.Model): # 自增int型別,是主鍵 id = models.AutoField(primary_key=True) # name 是一個varchar型別,長度是32 name = models.CharField(max_length=32) pwd = models.CharField(max_length=32)
- pycharm終端實現資料庫的遷移操作
1 python3 manage.py makemigrations ----記錄一下資料庫的變化 2 python3 manage.py migrate ----將變化同步到資料庫中