Django 筆記(二) 新建 ~ 渲染
新建APP
python manange.py startapp app_name
然後右鍵 pycharm 的專案目錄,將新建的目錄從伺服器上下載進來
URL(Uniform Resoure Locator)統一資源定位符
格式:
http://127.0.0.1:8000/hello/
URL解釋:
schema://host[:port#]/path/.../[?query-string][#anchor]
schema:指定使用的協議(例如:http,https,ftp)
host:Http伺服器的IP地址或者域名
port:埠號,http預設是80埠
path:訪問資源的路徑
query-string:傳送給http伺服器的資料
anchor:錨點
urls.py的作用
path('test/<xx>/', views.test)
前面的url匹配成功後就會呼叫後面的檢視函式。
尖括號從url中捕獲值,包含一個轉化器型別(converter type)。
沒有轉化器,將匹配任意字串,當然也包括了 / 字元。
注:<xx> 必須與檢視函式的引數一致
例:def test(request, xx)
轉換器:
str:匹配除了路徑分隔符(/)之外的非空字串,這是預設的形式
int:匹配正整數,包含0
slug:匹配字母、數字以及橫槓、下劃線組成的字串
uuid:匹配格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00
path:匹配任何非空字串,包含了路徑分隔符
re_path 正則匹配:
可使用正則的方法匹配
include 的作用:
一個 project 有一個棕的 urls.py ,各個 app 也可以自己建立自己的 urls.py
用 include() 函式在project的 urls.py 檔案進行註冊
例:
from django.urls importpath, include from . import views urlpatterns = [ path('book/', include('book.urls')) ]
此時 APP books 裡面的 urls.py
from django.urls import path from . import views urlpatterns = [ path('index/', views.index) ]
此時 APP books 裡面的 views.py
from django.shortcuts import render def index(request): return render(request, '這是 book 的首頁')
kwargs 的作用:
不定長引數
如果在分 urls.py 添加了字典引數
path('book/',views.test, {‘switch’: 'true'})
views 下面的 test 函式形參需要額外增加一個 **kwargs
如果在使用了 include , 主 views 添加了 字典引數
其分之下所有函式形參都需要新增 **kwargs
name 的作用:
可以給 url 取名字,通過該名字找到對應 url,這樣左的原因是防止 url 的規則更改,導致使用了該 url 的地方也要更改,但如去了名字,就不要做任何改動了。
APP books裡的 urls.py
path('article_name/', views.article_new, name='new_article')
APP books 裡的 views.py
from django.shortcuts import render, reverse, redirect return redirect(reverse('new_article'))
注:redirect 是重定向(跳轉), reverse 是將 url 的 name 解析成 url 本身的函式
templates 模板:
該模板可新建各個以 app 命名的目錄存放各自 app 模板檔案
然後在 setting.py 中的模板路徑配置修改以下內容
TEMPLATES = [
'DIRS': [os.path.join(BASE_DIR, 'templates')],
]
渲染模板(三種方法選一,皆需 import 匯入才能使用):
1.直接將html字串硬編碼 HttpResponse 中
def index(request): return HttpResponse('<h1>Hello Django World!</h1>')
2. django.template.loader 定義了函式以載入模板
from django.template.loader import get_template def index(request): t = get_template('book/index.html') html = t.render() return HttpResponse(html)
3.使用 render 進行渲染(建議此方法)
def index(request): return render(request, 'book/index.html')