简单混合

ContextMixin

class django.views.generic.base.ContextMixin

Attributes

extra_context

包含在上下文中的词典。这是在中指定某些上下文的方便方法 as_view() . 示例用法:

from django.views.generic import TemplateView

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

Methods

get_context_data(**kwargs)

返回表示模板上下文的字典。提供的关键字参数将构成返回的上下文。示例用法:

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

所有基于类的通用视图的模板上下文包括 view 指向的变量 View 实例。

使用 alters_data 在适当的情况下

请注意,在模板上下文中拥有视图实例可能会向模板作者公开潜在的危险方法。要防止在模板中调用此类方法,请设置 alters_data=True 关于这些方法。有关详细信息,请阅读 rendering a template context .

TemplateResponseMixin

class django.views.generic.base.TemplateResponseMixin

提供一种机制来构造 TemplateResponse ,给定适当的上下文。要使用的模板是可配置的,可以通过子类进一步自定义。

Attributes

template_name

由字符串定义的要使用的模板的全名。不定义 template_name 将提高 django.core.exceptions.ImproperlyConfigured 例外。

template_engine

这个 NAME 用于加载模板的模板引擎。 template_engine 被作为 using 关键字参数 response_class . 默认是 None 它告诉Django在所有配置的引擎中搜索模板。

response_class

将由返回的响应类 render_to_response 方法。默认是 TemplateResponse . 模板和上下文 TemplateResponse 以后可以更改实例(例如 template response middleware

如果需要自定义模板加载或自定义上下文对象实例化,请创建 TemplateResponse 子类并将其分配给 response_class .

content_type

用于响应的内容类型。 content_type 作为关键字参数传递给 response_class . 默认是 None --意思是Django使用 'text/html' .

Methods

render_to_response(context, **response_kwargs)

返回A self.response_class 实例。

如果提供了任何关键字参数,它们将传递给响应类的构造函数。

调用 get_template_names() 获取要搜索的模板名称列表,以查找现有模板。

get_template_names()

返回呈现模板时要搜索的模板名称列表。将使用找到的第一个模板。

默认实现将返回一个包含 template_name (如有规定)。