1. 建立虛擬環境
建議python版本3以上
python3 -m venv venv 生成虛擬環境
source venv/bin/activate 將虛擬環境導出來,作爲環境變量直接執行
deactivate推出虛擬環境
pip install django -i https://pypi.douban.com/simple 在虛擬環境中安裝django
2. 第一個項目
django-admin startproject "項目名" 創建項目(我這裏叫first_project)
mv venv first_project/ 因爲是一套東西所以放在一起
用pycharm打開該項目,然後將venu排除,因爲其本身跟邏輯沒有任何關係
注意:我這裏發現移動完虛擬環境後,不能用虛擬環境的python了,我又重新在first_project下重新生成的虛擬環境並安裝django
用pycharm的終端新建app:django-admin startapp first_app
first_project/first_project/settings.py是全局配置文件,urls是路由
django遵循可插拔式的 plugable,就是每個app之前必應該有依賴的情況,保持獨立
3. MTV+urls
models:數據庫管理員,非必須的
template:模版引擎,從數據轉成模版語言,其實就是轉換器,非必須的
view:視圖,接口引擎,訪問url時,處理接口的邏輯,用來響應請求的,必須的
流程:
瀏覽器中輸入url->urls->views->models->數據庫->views->templates->response(字節碼)->瀏覽器
4. Hello World
在first_app中的views添加下面圖一代碼,在first_project中的urls中添加下圖二中的代碼
啓動服務
在這個例子中,定義了函數視圖,但是不推薦用,因爲這樣就失去了用Django的意義
要用官方推薦的方法,對項目的理解和擴展能力來講會更好
5. 路由分發例子
新建first_app/urls.py文件
1 from django.http import HttpResponse 2 3 def index(request): 4 return HttpResponse("i am first app")
from django.urls import path from . import views urlpatterns = [ path('', views.index), ]
from django.contrib import admin from django.urls import path, include from first_app import urls as first_app_urls urlpatterns = [ path('admin/', admin.site.urls), path('first_app/', include(first_app_urls)) ]
分發到子app中路由時,需要調用include函數
5. 正則匹配路由
from django.urls import path from . import views urlpatterns = [ path('<int:num>/', views.index), ]
其他代碼不變
這樣在請求url時可以匹配到127.0.0.1:8000/test/1/這個url中test後面的1了
6. 模版視圖
a.函數視圖
推薦在每個app中新建templates
# first_app/views.py from django.template.response import TemplateResponse def index(request, *args, **kwargs): return TemplateResponse(request, 'first_app/index.html')
<!-- fist_app/template/fist_app/index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p style="background-color: blue">Hello</p> </body> </html>
# fist_project/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'first_app.apps.FirstAppConfig' #新加行 ]
效果圖
⚠️不提倡用函數視圖,只是瞭解有這種方法
b.模版視圖
# fist_app/views.py from django.views.generic import TemplateView class TestView(TemplateView):# 繼承TemplateView template_name = 'first_app/index.html' # 只需要重新定義下這個參數,即html路徑
# first_app/urls.py from django.urls import path from . import views urlpatterns = [ path('<int:num>/', views.TestView.as_view()), # as_view函數就轉成視圖,也可以穿參數 ]
效果和函數視圖一樣
c.渲染模版
# first_app/views.py from django.views.generic import TemplateView class TestView(TemplateView):# 繼承TemplateView template_name = 'first_app/index.html' # 只需要重新定義下這個參數,即html路徑 def get_context_data(self, **kwargs):# 這個函數用來渲染模版 return {'word': 'hello world'}
<!-- 兩個大括號是模版語言 --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p style="background-color: green">{{ word }}</p> </body> </html>
效果和上面一樣