ContextMixin¶属性
一个包含在上下文中的字典。这是在 as_view() 中指定一些上下文的方便方法。使用示例:
from django.views.generic import TemplateView
TemplateView.as_view(extra_context={"title": "Custom Title"})
方法
返回一个代表模板上下文的字典。提供的关键字参数将构成返回的上下文。示例用法:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["number"] = random.randrange(1, 100)
return context
所有基于类的通用视图的模板上下文包括一个指向 View 实例的 view 变量。
酌情使用 alters_data。
Note that having the view instance in the template context may
expose potentially hazardous methods to template authors. To
prevent methods like this from being called in the template, set
alters_data=True on those methods. For more information, read
the documentation on rendering a template context.
TemplateResponseMixin¶提供一个机制来构造一个 TemplateResponse,给定合适的上下文。使用的模板是可配置的,可以通过子类进一步定制。
属性
要使用的模板的全称,由一个字符串定义。如果没有定义 template_name 将引发一个 django.core.exceptions.ImproperlyConfigured 异常。
用于加载模板的模板引擎的 NAME。template_engine 作为 using 关键字参数传递给 response_class。默认值是 None,它告诉 Django 在所有配置的引擎中搜索模板。
render_to_response 方法要返回的响应类,默认为 TemplateResponse。TemplateResponse 实例的模板和上下文可以在以后进行修改(例如在 模板响应中间件)。
如果你需要自定义模板加载或自定义上下文对象实例化,请创建一个 TemplateResponse 子类,并将其分配给 response_class。
响应要使用的内容类型。content_type 作为 response_class 的关键字参数传递。默认值是 None——意味着 Django 使用 'text/html'。
方法
返回一个 self.response_class 实例。
如果提供任何关键字参数,它们将被传递给响应类的构造函数。
Calls get_template_names() to obtain the list of template names
that will be searched looking for an existent template.
返回渲染模板时要搜索的模板名称列表。找到的第一个模板将被使用。
默认的实现将返回一个包含 template_name 的列表(如果指定了)。
12月 22, 2025