Django基本配置
Python的WEB框架有Django、Tornado、Flask 等多種,Django相較與其餘WEB框架其優點爲:大而全,框架自己集成了ORM、模型綁定、模板引擎、緩存、Session等諸多功能css
1.安裝
# windows 直接用pip進行安裝
pip install django
# 生成的django文件加入到系統環境變量
2.建立並啓動
建立 django-admin startproject mysite 運行 python manage.py runserver 127.0.0.1:8001
瀏覽器訪問:
http://127.0.0.1:8001/
3.mysite目錄結構
mysite #目錄 - mysite # 對整個程序進行配置 - init - settings # 配置文件 - urls # URL對應關係 - wsgi # 遵循WSIG規範,uwsgi + nginx - manage.py # 管理Django程序:
Django業務配置
1.建立app
python manage.py startapp cmdb -->Terminal裏面運行
2.app目錄結構
# 目錄結構 - cmdb - migrations #數據庫操做記錄(只是修改表結構的記錄) - init #表示python數據包(python3中有無都可) - admin #Django爲咱們提供的後臺管理 - apps #配置當前app - models #建立數據庫表結構,寫指定的類,經過命令能夠建立數據庫結構 - tests #單元測試 - views #寫業務邏輯代碼,最重要的就是這個文件了
3.templates模板
(1)在templates目錄下生成要給用戶顯示的登陸頁面html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> label{ width: 80px; text-align: right; display: inline-block; } </style> </head> <body> <form action="/login" method="post"> <p> <label for="username">用戶名:</label> <input id="username" name="user" type="text" /> </p> <p> <label for="password">密碼:</label> <input id="password" name="pwd" type="password" /> <input type="submit" value="提交" /> </p> </form> </body> </html>
(2)修改urls文件增長login路徑python
from django.conf.urls import url from django.contrib import admin from cmdb import views #導入views模塊 urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login', views.login), #添加login.html的url,後面要加逗號 ]
(3)修改view文件,對數據進行處理nginx
from django.shortcuts import HttpResponse from django.shortcuts import render def login(request): return render(request,'login.html') # 上面代碼等同於這個 # f = open('templates/login.html','r',encoding='utf-8') # data = f.read() # f.close() # return HttpResponse(data)
(4)配置靜態文件static路徑數據庫
靜態文件static裏面是存放css和js文件的,要想顯示相應的樣式,必須先修改settings文件配置django
# settings.py文件裏增長下面內容
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
配置完路勁後就能夠用css和js文件了windows
Django表單交互
1.獲取表單提交類型作相應處理,用戶名密碼輸正確跳轉到頁面,輸入錯誤有提示信息
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/commons.css" /> <style> label{ width: 80px; text-align: right; display: inline-block; } </style> </head> <body> <form action="/login/" method="post"> <p> <label for="username">用戶名:</label> <input id="username" name="user" type="text" /> </p> <p> <label for="password">密碼:</label> <input id="password" name="pwd" type="password" /> <input type="submit" value="提交" /> <span style="color: red;">{{ error_msg }}</span> </p> </form> </body> </html>
from django.shortcuts import HttpResponse from django.shortcuts import render from django.shortcuts import redirect def login(request): # request 包含了用戶提交的全部信息 # print(request.method) error_msg = '' if request.method == 'POST': user = request.POST.get('user', None) pwd = request.POST.get('pwd', None) if user == 'root' and pwd == '123': # 去跳轉 return redirect('http://www.baidu.com') else: error_msg = '用戶名或密碼錯誤' return render(request, 'login.html', {'error_msg': error_msg})
2.模擬數據庫交互
訪問login界面,用戶輸入用戶名跳轉到home頁面瀏覽器
(1)登錄頁面緩存
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/commons.css" /> <style> label{ width: 80px; text-align: right; display: inline-block; } </style> </head> <body> <form action="/login/" method="post"> <p> <label for="username">用戶名:</label> <input id="username" name="user" type="text" /> </p> <p> <label for="password">密碼:</label> <input id="password" name="pwd" type="password" /> <input type="submit" value="提交" /> <span style="color: red;">{{ error_msg }}</span> </p> </form> </body> </html>
(2)home頁面app
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body style="margin: 0"> <div style="height: 48px;background-color: #dddddd"></div> <div> <form action="/home/" method="post"> <input type="text" name="username" placeholder="用戶名" /> <input type="text" name="email" placeholder="郵箱"/> <input type="text" name="gender" placeholder="性別"/> <input type="submit" value="添加" /> </form> </div> <div> <table> {% for row in user_list %} <tr> <td>{{ row.username }}</td> <td>{{ row.gender }}</td> <td>{{ row.email }}</td> </tr> {% endfor %} </table> </div> </body> </html>
(3)修改view文件,對輸入的內容進行處理
from django.shortcuts import HttpResponse from django.shortcuts import render from django.shortcuts import redirect def login(request): # request 包含了用戶提交的全部信息 # print(request.method) error_msg = '' if request.method == 'POST': user = request.POST.get('user', None) pwd = request.POST.get('pwd', None) if user == 'root' and pwd == '123': # 去跳轉 return redirect('/home') else: error_msg = '用戶名或密碼錯誤' return render(request, 'login.html', {'error_msg': error_msg}) USER_LIST = [ {'id': 1, 'username': 'derek', 'email': '111', "gender": '男'}, {'id': 2, 'username': 'jack', 'email': '222', "gender": '女'}, {"id": 3, 'username': 'tom', 'email': '333', "gender": '男'}, ] def home(request): if request.method == "POST": # 獲取用戶提交的數據 POST請求中 u = request.POST.get('username') e = request.POST.get('email') g = request.POST.get('gender') temp = {'username': u, 'email': e, "gender": g} USER_LIST.append(temp) return render(request, 'home.html', {'user_list': USER_LIST})
3.獲取checkbox多個值
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login/" method="POST" > <p> 111:<input type="checkbox" name="favor" value="11"/> 222:<input type="checkbox" name="favor" value="22"/> 333:<input type="checkbox" name="favor" value="33"/> </p> <input type="submit" value="提交"/> </form> </body> </html>
修改views.py文件對錶單處理
from django.shortcuts import HttpResponse from django.shortcuts import render from django.shortcuts import redirect def login(request): #checkbox 多選框 if request.method == "POST": favor_list = request.POST.getlist("favor") #getlist獲取多個值 print(favor_list) #多選框獲取到的是列表格式 #['11', '22', '33'] return render(request,"login.html") elif request.method == "GET": return render(request,"login.html") else: print("other")
當用戶提交以後,在後臺上能夠獲取用戶提交的信息,以下圖
4.上傳文件file
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login" method="POST" enctype="multipart/form-data"> <p> <input type="file" name="files"/> </p> <input type="submit" value="提交"/> </form> </body> </html>
views.py
from django.shortcuts import render,HttpResponse import os def login(request): #file 上傳文件 if request.method == "POST": obj = request.FILES.get('files') #用files獲取文件對象 if obj: print(obj, type(obj), obj.name) # test.jpg <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> test.jpg import os file_path = os.path.join('upload', obj.name) #保存用戶上傳文件的路勁 f = open(file_path, "wb") for item in obj.chunks(): #chunks表示全部的數據塊,是個迭代器 f.write(item) f.close() return render(request,"login.html") elif request.method == "GET": return render(request,"login.html") else: print("other")