這是Django MTV開發模式中的 T模塊 —— 模板系統, 作為django的一個非常重要的部分,也是我們學習的一個重要點,
?
官方定義: 作為一個Web框架,Django需要一種動態生成HTML的便捷方法,最常用的方法依賴于模板,模板包含所需HTML輸出的靜態部分以及描述動態內容將被插入的一些特殊語法,
這篇文章主要介紹了關于 django 的模板系統 T 層,工具: pycharm 2020
< django 從入門到放棄> 第五篇
沙漏在下雨
文章目錄
- 模板系統:
- 模板的配置:
- 模板的加載和回應方式:
- render() 方式解釋:
模板系統:
在 Django 中我們把“模板”稱之為 Template,它的存在使得 HTML 和 View 視圖層實作了解耦, 在去 前文 MTV 開發模式中我們也提到過 Template,它是設計模式中的 T 層,那么它在 Djang 中又是如何應用的呢?
其實 T 層應用是這樣實作,當創建好一個 Django 專案后,我們在專案的同級目錄下創建一個名為 templates 檔案夾,對它進行簡單的配置后,這個檔案夾將被 Django 自動識別,我們可以簡單的理解為:檔案夾就好比我們所說的 T 層,然而其復雜的實作程序由 Django 框架本身來實作的,所以我們無需關心內部細節,
模板的配置:
在 Django 中,模板是可以根據字典資料動態變化的,并且能夠根據視圖中傳遞的字典資料動態生成相應的 HTML 網頁,Django 中使用 Template 來表示模板,Template 物件定義在 django/template/base.py 檔案中,它的建構式原始碼如下:
def __init__(self, template_string, origin=None, name=None, engine=None):
# If Template is instantiated directly rather than from an Engine and
# exactly one Django template engine is configured, use that engine.
# This is required to preserve backwards-compatibility for direct use
# e.g. Template('...').render(Context({...}))
if engine is None:
from .engine import Engine
engine = Engine.get_default()
if origin is None:
origin = Origin(UNKNOWN_SOURCE)
self.name = name
self.origin = origin
self.engine = engine
self.source = str(template_string) # May be lazy.
self.nodelist = self.compile_nodelist()
這個原始碼看不懂沒關系, 按照步驟來, 都是這么來的,
- 首先 新建 templates 于 nowapp 下一級的目錄下,如下:
├─nowapp
│ ├─migrations
│ │ └─__pycache__
│ ├─templates
│ └─__pycache__
└─nowproject
└─__pycache__
- 然后在setting.py 檔案中,找到TEMPLATES, 按照如下設定
- 主要是增加 DIRS 里面的模板位置
# setting.py
import os
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'nowapp\\templates\\')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
其中關于TEMPPLAETS的欄位解釋:
- BACKEND : Django默認設定,指定了要是用的模板引擎的 Python 路徑;
- DIRS : 一個目錄串列,指定模板檔案的存放路徑,可以是一個或者多個,模板引擎將按照串列中定義的順序查找模板檔案;
- APP_DIRS : 一個布林值,默認為 Ture,表示會在安裝應用中的 templates 目錄中搜索所有模板檔案;
- OPTIONS : 指定額外的選項,不同的模板引擎有著不同的可選引數,例如 context_processors 用于配置模板背景關系處理器,在使 RequestContext 時將看到它們的作用,
模板的加載和回應方式:
關于模板的加載和回應方式,django提供了2中方式,
- 使用 loader 獲取模板, 然后使用 HttpResponse 進行回應
- 直接使用 render 方法加載回應模板 (主要使用這個方法 )
方法介紹如下:
from django.template import loader # 匯入loader方法
from django.shortcuts import render #匯入render 方法
#方式一
def test_html(request):
t=loader.get_template('test.html')
html=t.render({'name':'第一種'} #以字典形式傳遞資料并生成html
return HttpResponse(html) #以 HttpResponse方式回應html
#方式二
from django.shortcuts import render #匯入reder方法
def test_html(request):
return render(request,'test.html',{'name':'第二種'})#根據字典資料生成動態模板
# 方式二的其他方式(推薦)
def test_html(request):
name = "第二種"
return render(request, 'test.html', locals())
render() 方式解釋:
renbder 方法的作用是結合一個給定的模板和一個給定的字典,并回傳一個渲染后的 HttpResponse 物件,通俗的講就是把字典格式的內容, 加載進 templates 目錄中定義的 HTML 檔案, 最終通過瀏覽器渲染呈現. 關于render 我們查看他的原始碼,發現他的構造方式如下:
render(request, template_name,
context=None,
content_type=None,
status=None,
using=None)
關于引數的含義如下:
-
request: 是一個固定引數,用于生成回應的請求物件, 這個一定要填入 ;
-
template_name: templates 中定義的檔案, 要注意路徑名, 一般使用 nowapp/test.html ;
-
context: 要傳入檔案中用于渲染呈現的資料, 默認是字典格式, 或者直接使用 locals() 直接把所有引數構造成字典回傳;
-
content_type: 生成的檔案要使用的媒體格式型別,默認為 DEFAULT_CONTENT_TYPE 設定的值;
-
status: http 的回應代碼,默認是 200;
-
using: 用于加載模板使用的模板引擎的名稱,
其中關于 content_type 這個引數其實有很多欄位描述的, 找到了一個資料,如下:
- 1. text/html : HTML 格式
- text/csv: csv格式
- text/plain :純文本格式
- text/xml : XML 格式
- image/gif :gif 圖片格式
- image/jpeg :jpg 圖片格式
- image/png:png 圖片格式
- application/xhtml+xml :XHTML 格式
- application/xml: XML 資料格式
- application/atom+xml :Atom XML 聚合格式
- application/json: JSON 資料格式
- application/pdf:pdf 格式
- application/msword :Word 檔案格式
- application/octet-stream : 二進制流資料(如常見的檔案下載)
- application/x-www-form-urlencoded :form 表單資料被編碼為
- key/value 格式發送到服務器(表單默認的提交資料的格式),
- multipart/form-data : 需要在表單中進行檔案上傳時,就需要使用該格式
下一篇博客我們介紹一下關于Django 模板的四大組成部分, 變數, 標簽, 過濾器,以及注釋, 翻譯至官網檔案,不足之處請指教,
ps: 文章主要是用來記錄自己的學習情況, 很多我也不會,也就是個菜雞了,
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/208493.html
標籤:其他
上一篇:基于tf2的dl編程學習(零)
下一篇:python3.9下錯誤,pip安裝matplotlib卡在Building wheel for matplotlib (setup.py)..不動的原因與解決
