簡單 Mixins

ContextMixin

class django.views.generic.base.ContextMixin

屬性

extra_context

一個要包含在 context 中的字典。這是一種在 as_view() 中指定 context 的方便方式。使用範例

from django.views.generic import TemplateView

TemplateView.as_view(extra_context={"title": "Custom Title"})

方法

get_context_data(**kwargs)

返回一個表示模板 context 的字典。提供的關鍵字參數將構成返回的 context。使用範例

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context["number"] = random.randrange(1, 100)
    return context

所有基於類別的通用視圖的模板 context 都包含一個指向 View 實例的 view 變數。

在適當的地方使用 alters_data

請注意,在模板 context 中具有視圖實例可能會將潛在的危險方法暴露給模板作者。為了防止在模板中調用此類方法,請在這些方法上設定 alters_data=True。如需更多資訊,請閱讀關於 渲染模板 context 的文件。

TemplateResponseMixin

class django.views.generic.base.TemplateResponseMixin

提供一種機制來建構 TemplateResponse,給定適當的 context。要使用的模板是可配置的,並且可以由子類別進一步自訂。

屬性

template_name

以字串定義的要使用的模板完整名稱。不定義 template_name 會引發 django.core.exceptions.ImproperlyConfigured 例外。

template_engine

用於載入模板的模板引擎的 NAMEtemplate_engine 會作為 using 關鍵字引數傳遞給 response_class。預設值為 None,這會告知 Django 在所有已設定的引擎中搜尋模板。

response_class

render_to_response 方法返回的 response class。預設值為 TemplateResponse。稍後可以更改 TemplateResponse 實例的模板和 context (例如,在 模板回應中介軟體中)。

如果您需要自訂模板載入或自訂 context 物件實例化,請建立 TemplateResponse 子類別並將其指派給 response_class

content_type

用於回應的內容類型。content_type 會作為關鍵字引數傳遞給 response_class。預設值為 None – 表示 Django 使用 'text/html'

方法

render_to_response(context, **response_kwargs)

返回一個 self.response_class 實例。

如果提供任何關鍵字引數,它們將會傳遞給 response class 的建構函式。

呼叫 get_template_names() 以取得將會搜尋是否存在模板的模板名稱清單。

get_template_names()

返回渲染模板時要搜尋的模板名稱清單。將會使用找到的第一個模板。

預設實作會返回一個包含 template_name 的清單 (如果已指定)。

返回頂端