简单的mixins

ContextMixin

class django.views.generic.base.ContextMixin

Attributes

extra_context
New in Django 2.0.

要包含在上下文中的字典。 这是在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变量​​。

Use alters_data where appropriate

请注意,在模板上下文中使用视图实例可能会向模板作者公开具有潜在危险的方法。 要防止在模板中调用此类方法,请在这些方法上设置alters_data = True 有关更多信息,请阅读呈现模板上下文的文档。

TemplateResponseMixin

class django.views.generic.base.TemplateResponseMixin

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

Attributes

template_name

要由字符串定义使用的模板的全名。 未定义template_name将引发django.core.exceptions.ImproperlyConfigured异常。

template_engine

The NAME of a template engine to use for loading the template. template_engine is passed as the using keyword argument to response_class. Default is None, which tells Django to search for the template in all configured engines.

response_class

render_to_response方法返回的响应类。 Default is TemplateResponse. TemplateResponse实例的模板和上下文可以稍后更改(例如,在模板响应中间件中)。

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

content_type

用于响应的内容类型。 content_type作为关键字参数传递给response_class 默认值为 - 表示Django使用DEFAULT_CONTENT_TYPE

Methods

render_to_response(context, **response_kwargs)

返回self.response_class实例。

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

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

get_template_names()

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

如果指定了template_name,则默认实现将返回包含template_name的列表(如果已指定)。