“Django/docs/3.0.x/ref/template-response”的版本间差异

来自菜鸟教程
Django/docs/3.0.x/ref/template-response
跳转至:导航、​搜索
(autoload)
 
(Page commit)
 
第1行: 第1行:
 +
{{DISPLAYTITLE:TemplateResponse 和 SimpleTemplateResponse — Django 文档}}
 
<div id="module-django.template.response" class="section">
 
<div id="module-django.template.response" class="section">
  
 
<span id="templateresponse-and-simpletemplateresponse"></span>
 
<span id="templateresponse-and-simpletemplateresponse"></span>
= <code>TemplateResponse</code> and <code>SimpleTemplateResponse</code> =
+
= TemplateResponse SimpleTemplateResponse =
  
Standard [[../request-response#django.http|<code>HttpResponse</code>]] objects are static structures.
+
标准 [[../request-response#django.http|HttpResponse]] 对象是静态结构。 它们在构建时提供了一个预渲染的内容块,虽然该内容可以修改,但它的形式并不容易执行修改。
They are provided with a block of pre-rendered content at time of
 
construction, and while that content can be modified, it isn't in a form that
 
makes it easy to perform modifications.
 
  
However, it can sometimes be beneficial to allow decorators or
+
然而,有时允许装饰器或中间件在视图构造响应 ''之后修改响应'' 是有益的。 例如,您可能想要更改所使用的模板,或将附加数据放入上下文中。
middleware to modify a response ''after'' it has been constructed by the
 
view. For example, you may want to change the template that is used,
 
or put additional data into the context.
 
  
TemplateResponse provides a way to do just that. Unlike basic
+
TemplateResponse 提供了一种方法来做到这一点。 与基本的 [[../request-response#django.http|HttpResponse]] 对象不同,TemplateResponse 对象保留了视图提供的模板和上下文的详细信息以计算响应。 响应的最终输出在需要时才计算,在响应过程的后期。
[[../request-response#django.http|<code>HttpResponse</code>]] objects, TemplateResponse objects retain
 
the details of the template and context that was provided by the view to
 
compute the response. The final output of the response is not computed until
 
it is needed, later in the response process.
 
  
 
<div id="simpletemplateresponse-objects" class="section">
 
<div id="simpletemplateresponse-objects" class="section">
  
== <code>SimpleTemplateResponse</code> objects ==
+
== SimpleTemplateResponse 物体 ==
  
; ''class'' <code>SimpleTemplateResponse</code>
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">SimpleTemplateResponse</span></span>
 
:  
 
:  
  
第32行: 第23行:
  
 
<dl>
 
<dl>
<dt><code>SimpleTemplateResponse.</code><code>template_name</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">SimpleTemplateResponse.</span></span><span class="sig-name descname"><span class="pre">template_name</span></span></dt>
<dd><p>The name of the template to be rendered. Accepts a backend-dependent
+
<dd><p>要呈现的模板的名称。 接受依赖于后端的模板对象(例如由 [[../../topics/templates#django.template.loader|get_template()]] 返回的对象)、模板名称或模板名称列表。</p>
template object (such as those returned by
+
<p>示例:<code>['foo.html', 'path/to/bar.html']</code></p></dd></dl>
[[../../topics/templates#django.template.loader|<code>get_template()</code>]]), the name of a template,
 
or a list of template names.</p>
 
<p>Example: <code>['foo.html', 'path/to/bar.html']</code></p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>SimpleTemplateResponse.</code><code>context_data</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">SimpleTemplateResponse.</span></span><span class="sig-name descname"><span class="pre">context_data</span></span></dt>
<dd><p>The context data to be used when rendering the template. It must be a
+
<dd><p>渲染模板时要使用的上下文数据。 它必须是 <code>dict</code></p>
<code>dict</code>.</p>
+
<p>示例:<code>{'foo': 123}</code></p></dd></dl>
<p>Example: <code>{'foo': 123}</code></p></dd></dl>
 
  
; <code>SimpleTemplateResponse.</code><code>rendered_content</code>
+
; <span class="sig-prename descclassname"><span class="pre">SimpleTemplateResponse.</span></span><span class="sig-name descname"><span class="pre">rendered_content</span></span>
: The current rendered value of the response content, using the current template and context data.
+
: 响应内容的当前呈现值,使用当前模板和上下文数据。
  
; <code>SimpleTemplateResponse.</code><code>is_rendered</code>
+
; <span class="sig-prename descclassname"><span class="pre">SimpleTemplateResponse.</span></span><span class="sig-name descname"><span class="pre">is_rendered</span></span>
: A boolean indicating whether the response content has been rendered.
+
: 指示响应内容是否已呈现的布尔值。
  
  
第57行: 第44行:
 
=== 方法 ===
 
=== 方法 ===
  
; <code>SimpleTemplateResponse.</code><code>__init__</code><span class="sig-paren">(</span>''<span class="n">template</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">content_type</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">status</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">charset</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">using</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">SimpleTemplateResponse.</span></span><span class="sig-name descname"><span class="pre">__init__</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">template</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">content_type</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">status</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">charset</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">using</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span>
: Instantiates a [[#django.template.response.SimpleTemplateResponse|<code>SimpleTemplateResponse</code>]] object with the given template, context, content type, HTTP status, and charset.
+
: 使用给定的模板、上下文、内容类型、HTTP 状态和字符集实例化 [[#django.template.response.SimpleTemplateResponse|SimpleTemplateResponse]] 对象。
 
;; <code>template</code>
 
;; <code>template</code>
;: A backend-dependent template object (such as those returned by [[../../topics/templates#django.template.loader|<code>get_template()</code>]]), the name of a template, or a list of template names.
+
;: 依赖于后端的模板对象(例如由 [[../../topics/templates#django.template.loader|get_template()]] 返回的对象)、模板名称或模板名称列表。
 
;; <code>context</code>
 
;; <code>context</code>
;: A <code>dict</code> of values to add to the template context. By default, this is an empty dictionary.
+
;: 要添加到模板上下文的 <code>dict</code> 值。 默认情况下,这是一个空字典。
 
;; <code>content_type</code>
 
;; <code>content_type</code>
;: The value included in the HTTP <code>Content-Type</code> header, including the MIME type specification and the character set encoding. If <code>content_type</code> is specified, then its value is used. Otherwise, <code>'text/html'</code> is used.
+
;: HTTP <code>Content-Type</code> 标头中包含的值,包括 MIME 类型规范和字符集编码。 如果指定了 <code>content_type</code>,则使用其值。 否则,使用 <code>'text/html'</code>
 
;; <code>status</code>
 
;; <code>status</code>
;: The HTTP status code for the response.
+
;: 响应的 HTTP 状态代码。
 
;; <code>charset</code>
 
;; <code>charset</code>
;: The charset in which the response will be encoded. If not given it will be extracted from <code>content_type</code>, and if that is unsuccessful, the [[../settings#std-setting-DEFAULT_CHARSET|<code>DEFAULT_CHARSET</code>]] setting will be used.
+
;: 响应将在其中编码的字符集。 如果没有给出,它将从 <code>content_type</code> 中提取,如果不成功,将使用 [[#id1|:setting:`DEFAULT_CHARSET`]] 设置。
 
;; <code>using</code>
 
;; <code>using</code>
;: 用于加载模板的模板引擎的 :setting:[[#id1|<span id="id2" class="problematic">`</span>]]NAME ` 。
+
;: [[#id3|:setting:`名称 `]] 用于加载模板的模板引擎。
  
 
<dl>
 
<dl>
<dt><code>SimpleTemplateResponse.</code><code>resolve_context</code><span class="sig-paren">(</span>''<span class="n">context</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">SimpleTemplateResponse.</span></span><span class="sig-name descname"><span class="pre">resolve_context</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">context</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Preprocesses context data that will be used for rendering a template.
+
<dd><p>预处理将用于渲染模板的上下文数据。 接受上下文数据的 <code>dict</code>。 默认情况下,返回相同的 <code>dict</code></p>
Accepts a <code>dict</code> of context data. By default, returns the same
+
<p>重写此方法以自定义上下文。</p></dd></dl>
<code>dict</code>.</p>
 
<p>Override this method in order to customize the context.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>SimpleTemplateResponse.</code><code>resolve_template</code><span class="sig-paren">(</span>''<span class="n">template</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">SimpleTemplateResponse.</span></span><span class="sig-name descname"><span class="pre">resolve_template</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">template</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Resolves the template instance to use for rendering. Accepts a
+
<dd><p>解析用于渲染的模板实例。 接受依赖于后端的模板对象(例如由 [[../../topics/templates#django.template.loader|get_template()]] 返回的对象)、模板名称或模板名称列表。</p>
backend-dependent template object (such as those returned by
+
<p>返回要呈现的后端相关模板对象实例。</p>
[[../../topics/templates#django.template.loader|<code>get_template()</code>]]), the name of a template,
+
<p>重写此方法以自定义模板加载。</p></dd></dl>
or a list of template names.</p>
 
<p>Returns the backend-dependent template object instance to be rendered.</p>
 
<p>Override this method in order to customize template loading.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>SimpleTemplateResponse.</code><code>add_post_render_callback</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">SimpleTemplateResponse.</span></span><span class="sig-name descname"><span class="pre">add_post_render_callback</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Add a callback that will be invoked after rendering has taken
+
<dd><p>添加将在渲染发生后调用的回调。 此钩子可用于将某些处理操作(例如缓存)推迟到渲染发生之后。</p>
place. This hook can be used to defer certain processing
+
<p>如果 [[#django.template.response.SimpleTemplateResponse|SimpleTemplateResponse]] 已经被渲染,回调将被立即调用。</p>
operations (such as caching) until after rendering has occurred.</p>
+
<p>调用时,回调将传递一个参数 - 呈现的 [[#django.template.response.SimpleTemplateResponse|SimpleTemplateResponse]] 实例。</p>
<p>If the [[#django.template.response.SimpleTemplateResponse|<code>SimpleTemplateResponse</code>]]
+
<p>如果回调返回的值不是 <code>None</code>,这将用作响应而不是原始响应对象(并将传递给下一个渲染后回调等)</p></dd></dl>
has already been rendered, the callback will be invoked
 
immediately.</p>
 
<p>When called, callbacks will be passed a single argument -- the
 
rendered [[#django.template.response.SimpleTemplateResponse|<code>SimpleTemplateResponse</code>]]
 
instance.</p>
 
<p>If the callback returns a value that is not <code>None</code>, this will be
 
used as the response instead of the original response object (and
 
will be passed to the next post rendering callback etc.)</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>SimpleTemplateResponse.</code><code>render</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">SimpleTemplateResponse.</span></span><span class="sig-name descname"><span class="pre">render</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Sets <code>response.content</code> to the result obtained by
+
<dd><p><code>response.content</code> 设置为 [[#django.template.response.SimpleTemplateResponse.rendered_content|SimpleTemplateResponse.rendered_content]] 获得的结果,运行所有渲染后回调,并返回结果响应对象。</p>
[[#django.template.response.SimpleTemplateResponse.rendered_content|<code>SimpleTemplateResponse.rendered_content</code>]], runs all post-rendering
+
<p><code>render()</code> 只会在第一次被调用时产生效果。 在后续调用中,它将返回从第一次调用中获得的结果。</p></dd></dl>
callbacks, and returns the resulting response object.</p>
 
<p><code>render()</code> will only have an effect the first time it is called. On
 
subsequent calls, it will return the result obtained from the first call.</p></dd></dl>
 
  
  
第117行: 第88行:
 
<div id="templateresponse-objects" class="section">
 
<div id="templateresponse-objects" class="section">
  
== <code>TemplateResponse</code> objects ==
+
== TemplateResponse 物体 ==
  
; ''class'' <code>TemplateResponse</code>
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">TemplateResponse</span></span>
: <code>TemplateResponse</code> is a subclass of [[#django.template.response.SimpleTemplateResponse|<code>SimpleTemplateResponse</code>]] that knows about the current [[../request-response#django.http|<code>HttpRequest</code>]].
+
: <code>TemplateResponse</code> [[#django.template.response.SimpleTemplateResponse|SimpleTemplateResponse]] 的子类,它知道当前的 [[../request-response#django.http|HttpRequest]]
  
<div id="id1" class="section">
+
<div id="id5" class="section">
  
 
=== 方法 ===
 
=== 方法 ===
  
; <code>TemplateResponse.</code><code>__init__</code><span class="sig-paren">(</span>''<span class="n">request</span>'', ''<span class="n">template</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">content_type</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">status</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">charset</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">using</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">TemplateResponse.</span></span><span class="sig-name descname"><span class="pre">__init__</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">request</span></span>'', ''<span class="n"><span class="pre">template</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">content_type</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">status</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">charset</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">using</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span>
: Instantiates a [[#django.template.response.TemplateResponse|<code>TemplateResponse</code>]] object with the given request, template, context, content type, HTTP status, and charset.
+
: 使用给定的请求、模板、上下文、内容类型、HTTP 状态和字符集实例化 [[#django.template.response.TemplateResponse|TemplateResponse]] 对象。
 
;; <code>request</code>
 
;; <code>request</code>
;: An [[../request-response#django.http|<code>HttpRequest</code>]] instance.
+
;: [[../request-response#django.http|HttpRequest]] 实例。
 
;; <code>template</code>
 
;; <code>template</code>
;: A backend-dependent template object (such as those returned by [[../../topics/templates#django.template.loader|<code>get_template()</code>]]), the name of a template, or a list of template names.
+
;: 依赖于后端的模板对象(例如由 [[../../topics/templates#django.template.loader|get_template()]] 返回的对象)、模板名称或模板名称列表。
 
;; <code>context</code>
 
;; <code>context</code>
;: A <code>dict</code> of values to add to the template context. By default, this is an empty dictionary.
+
;: 要添加到模板上下文的 <code>dict</code> 值。 默认情况下,这是一个空字典。
 
;; <code>content_type</code>
 
;; <code>content_type</code>
;: The value included in the HTTP <code>Content-Type</code> header, including the MIME type specification and the character set encoding. If <code>content_type</code> is specified, then its value is used. Otherwise, <code>'text/html'</code> is used.
+
;: HTTP <code>Content-Type</code> 标头中包含的值,包括 MIME 类型规范和字符集编码。 如果指定了 <code>content_type</code>,则使用其值。 否则,使用 <code>'text/html'</code>
 
;; <code>status</code>
 
;; <code>status</code>
;: The HTTP status code for the response.
+
;: 响应的 HTTP 状态代码。
 
;; <code>charset</code>
 
;; <code>charset</code>
;: The charset in which the response will be encoded. If not given it will be extracted from <code>content_type</code>, and if that is unsuccessful, the [[../settings#std-setting-DEFAULT_CHARSET|<code>DEFAULT_CHARSET</code>]] setting will be used.
+
;: 响应将在其中编码的字符集。 如果没有给出,它将从 <code>content_type</code> 中提取,如果不成功,将使用 [[#id6|:setting:`DEFAULT_CHARSET`]] 设置。
 
;; <code>using</code>
 
;; <code>using</code>
;: 用于加载模板的模板引擎的 :setting:[[#id1|<span id="id2" class="problematic">`</span>]]NAME ` 。
+
;: [[#id8|:setting:`名称 `]] 用于加载模板的模板引擎。
  
  
第149行: 第120行:
 
<div id="the-rendering-process" class="section">
 
<div id="the-rendering-process" class="section">
  
== The rendering process ==
+
== 渲染过程 ==
  
Before a [[#django.template.response.TemplateResponse|<code>TemplateResponse</code>]] instance can be
+
在将 [[#django.template.response.TemplateResponse|TemplateResponse]] 实例返回给客户端之前,它必须被渲染。 渲染过程采用模板和上下文的中间表示,并将其转换为可以提供给客户端的最终字节流。
returned to the client, it must be rendered. The rendering process takes the
 
intermediate representation of template and context, and turns it into the
 
final byte stream that can be served to the client.
 
  
There are three circumstances under which a <code>TemplateResponse</code> will be
+
<code>TemplateResponse</code> 在三种情况下会被渲染:
rendered:
 
  
* When the <code>TemplateResponse</code> instance is explicitly rendered, using the [[#django.template.response.SimpleTemplateResponse.render|<code>SimpleTemplateResponse.render()</code>]] method.
+
* <code>TemplateResponse</code> 实例被显式渲染时,使用 [[#django.template.response.SimpleTemplateResponse.render|SimpleTemplateResponse.render()]] 方法。
* When the content of the response is explicitly set by assigning <code>response.content</code>.
+
* 通过分配<code>response.content</code>明确设置响应的内容时。
* After passing through template response middleware, but before passing through response middleware.
+
* 在通过模板响应中间件之后,但在通过响应中间件之前。
  
A <code>TemplateResponse</code> can only be rendered once. The first call to
+
<code>TemplateResponse</code> 只能渲染一次。 第一次调用 [[#django.template.response.SimpleTemplateResponse.render|SimpleTemplateResponse.render()]] 设置响应的内容; 后续渲染调用不会更改响应内容。
[[#django.template.response.SimpleTemplateResponse.render|<code>SimpleTemplateResponse.render()</code>]] sets the content of the response;
 
subsequent rendering calls do not change the response content.
 
  
However, when <code>response.content</code> is explicitly assigned, the
+
但是,当显式分配 <code>response.content</code> 时,将始终应用更改。 如果要强制重新渲染内容,可以重新评估渲染的内容,并手动分配响应的内容:
change is always applied. If you want to force the content to be
 
re-rendered, you can re-evaluate the rendered content, and assign
 
the content of the response manually:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第176行: 第138行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre># Set up a rendered TemplateResponse
+
<syntaxhighlight lang="python"># Set up a rendered TemplateResponse
&gt;&gt;&gt; from django.template.response import TemplateResponse
+
>>> from django.template.response import TemplateResponse
&gt;&gt;&gt; t = TemplateResponse(request, 'original.html', {})
+
>>> t = TemplateResponse(request, 'original.html', {})
&gt;&gt;&gt; t.render()
+
>>> t.render()
&gt;&gt;&gt; print(t.content)
+
>>> print(t.content)
 
Original content
 
Original content
  
 
# Re-rendering doesn't change content
 
# Re-rendering doesn't change content
&gt;&gt;&gt; t.template_name = 'new.html'
+
>>> t.template_name = 'new.html'
&gt;&gt;&gt; t.render()
+
>>> t.render()
&gt;&gt;&gt; print(t.content)
+
>>> print(t.content)
 
Original content
 
Original content
  
 
# Assigning content does change, no render() call required
 
# Assigning content does change, no render() call required
&gt;&gt;&gt; t.content = t.rendered_content
+
>>> t.content = t.rendered_content
&gt;&gt;&gt; print(t.content)
+
>>> print(t.content)
New content</pre>
+
New content</syntaxhighlight>
  
 
</div>
 
</div>
第199行: 第161行:
 
<div id="post-render-callbacks" class="section">
 
<div id="post-render-callbacks" class="section">
  
=== Post-render callbacks ===
+
=== 渲染后回调 ===
  
Some operations -- such as caching -- cannot be performed on an
+
某些操作(例如缓存)无法在未渲染的模板上执行。 它们必须在完全完整且呈现的响应上执行。
unrendered template. They must be performed on a fully complete and
 
rendered response.
 
  
If you're using middleware, you can do that. Middleware provides
+
如果您使用的是中间件,则可以这样做。 中间件提供了多种机会来处理退出视图时的响应。 如果您将行为放在响应中间件中,则保证在模板渲染发生后执行。
multiple opportunities to process a response on exit from a view. If
 
you put behavior in the response middleware, it's guaranteed to execute
 
after template rendering has taken place.
 
  
However, if you're using a decorator, the same opportunities do not
+
但是,如果您使用装饰器,则不存在相同的机会。 装饰器中定义的任何行为都会立即处理。
exist. Any behavior defined in a decorator is handled immediately.
 
  
To compensate for this (and any other analogous use cases),
+
为了弥补这一点(以及任何其他类似的用例),[[#django.template.response.TemplateResponse|TemplateResponse]] 允许您注册将在渲染完成时调用的回调。 使用此回调,您可以将关键处理推迟到可以保证呈现的内容可用的时间点。
[[#django.template.response.TemplateResponse|<code>TemplateResponse</code>]] allows you to register callbacks that will
 
be invoked when rendering has completed. Using this callback, you can
 
defer critical processing until a point where you can guarantee that
 
rendered content will be available.
 
  
To define a post-render callback, define a function that takes
+
要定义渲染后回调,请定义一个接受单个参数(响应)的函数,并将该函数注册到模板响应:
a single argument -- response -- and register that function with
 
the template response:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第227行: 第177行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from django.template.response import TemplateResponse
+
<syntaxhighlight lang="python">from django.template.response import TemplateResponse
  
 
def my_render_callback(response):
 
def my_render_callback(response):
第239行: 第189行:
 
     response.add_post_render_callback(my_render_callback)
 
     response.add_post_render_callback(my_render_callback)
 
     # Return the response
 
     # Return the response
     return response</pre>
+
     return response</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<code>my_render_callback()</code> will be invoked after the <code>mytemplate.html</code>
+
<code>my_render_callback()</code> 将在 <code>mytemplate.html</code> 渲染后调用,并将提供完全渲染的 [[#django.template.response.TemplateResponse|TemplateResponse]] 实例作为参数。
has been rendered, and will be provided the fully rendered
 
[[#django.template.response.TemplateResponse|<code>TemplateResponse</code>]] instance as an argument.
 
  
If the template has already been rendered, the callback will be
+
如果模板已经被渲染,回调将被立即调用。
invoked immediately.
 
  
  
第257行: 第204行:
 
<div id="using-templateresponse-and-simpletemplateresponse" class="section">
 
<div id="using-templateresponse-and-simpletemplateresponse" class="section">
  
== Using <code>TemplateResponse</code> and <code>SimpleTemplateResponse</code> ==
+
== 使用 TemplateResponse SimpleTemplateResponse ==
  
A [[#django.template.response.TemplateResponse|<code>TemplateResponse</code>]] object can be used anywhere that a normal
+
[[#django.template.response.TemplateResponse|TemplateResponse]] 对象可以在任何可以使用普通 [[../request-response#django.http|django.http.HttpResponse]] 的地方使用。 它也可以用作调用 [[../../topics/http/shortcuts#django.shortcuts|render()]] 的替代方法。
[[../request-response#django.http|<code>django.http.HttpResponse</code>]] can be used. It can also be used as an
 
alternative to calling [[../../topics/http/shortcuts#django.shortcuts|<code>render()</code>]].
 
  
For example, the following view returns a [[#django.template.response.TemplateResponse|<code>TemplateResponse</code>]] with a
+
例如,以下视图返回带有模板和包含查询集的上下文的 [[#django.template.response.TemplateResponse|TemplateResponse]]
template and a context containing a queryset:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第270行: 第214行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from django.template.response import TemplateResponse
+
<syntaxhighlight lang="python">from django.template.response import TemplateResponse
  
 
def blog_index(request):
 
def blog_index(request):
     return TemplateResponse(request, 'entry_list.html', {'entries': Entry.objects.all()})</pre>
+
     return TemplateResponse(request, 'entry_list.html', {'entries': Entry.objects.all()})</syntaxhighlight>
  
 
</div>
 
</div>
第282行: 第226行:
  
 
</div>
 
</div>
 +
<div class="clearer">
  
[[Category:Django 3.0.x 中文文档]]
+
 
 +
 
 +
</div>
 +
 
 +
[[Category:Django 3.0.x 文档]]

2021年10月31日 (日) 04:10的最新版本

TemplateResponse 和 SimpleTemplateResponse

标准 HttpResponse 对象是静态结构。 它们在构建时提供了一个预渲染的内容块,虽然该内容可以修改,但它的形式并不容易执行修改。

然而,有时允许装饰器或中间件在视图构造响应 之后修改响应 是有益的。 例如,您可能想要更改所使用的模板,或将附加数据放入上下文中。

TemplateResponse 提供了一种方法来做到这一点。 与基本的 HttpResponse 对象不同,TemplateResponse 对象保留了视图提供的模板和上下文的详细信息以计算响应。 响应的最终输出在需要时才计算,在响应过程的后期。

SimpleTemplateResponse 物体

class SimpleTemplateResponse

属性

SimpleTemplateResponse.template_name

要呈现的模板的名称。 接受依赖于后端的模板对象(例如由 get_template() 返回的对象)、模板名称或模板名称列表。

示例:['foo.html', 'path/to/bar.html']

SimpleTemplateResponse.context_data

渲染模板时要使用的上下文数据。 它必须是 dict

示例:{'foo': 123}

SimpleTemplateResponse.rendered_content
响应内容的当前呈现值,使用当前模板和上下文数据。
SimpleTemplateResponse.is_rendered
指示响应内容是否已呈现的布尔值。


方法

SimpleTemplateResponse.__init__(template, context=None, content_type=None, status=None, charset=None, using=None)
使用给定的模板、上下文、内容类型、HTTP 状态和字符集实例化 SimpleTemplateResponse 对象。
template
依赖于后端的模板对象(例如由 get_template() 返回的对象)、模板名称或模板名称列表。
context
要添加到模板上下文的 dict 值。 默认情况下,这是一个空字典。
content_type
HTTP Content-Type 标头中包含的值,包括 MIME 类型规范和字符集编码。 如果指定了 content_type,则使用其值。 否则,使用 'text/html'
status
响应的 HTTP 状态代码。
charset
响应将在其中编码的字符集。 如果没有给出,它将从 content_type 中提取,如果不成功,将使用 :setting:`DEFAULT_CHARSET` 设置。
using
:setting:`名称 ` 用于加载模板的模板引擎。
SimpleTemplateResponse.resolve_context(context)

预处理将用于渲染模板的上下文数据。 接受上下文数据的 dict。 默认情况下,返回相同的 dict

重写此方法以自定义上下文。

SimpleTemplateResponse.resolve_template(template)

解析用于渲染的模板实例。 接受依赖于后端的模板对象(例如由 get_template() 返回的对象)、模板名称或模板名称列表。

返回要呈现的后端相关模板对象实例。

重写此方法以自定义模板加载。

SimpleTemplateResponse.add_post_render_callback()

添加将在渲染发生后调用的回调。 此钩子可用于将某些处理操作(例如缓存)推迟到渲染发生之后。

如果 SimpleTemplateResponse 已经被渲染,回调将被立即调用。

调用时,回调将传递一个参数 - 呈现的 SimpleTemplateResponse 实例。

如果回调返回的值不是 None,这将用作响应而不是原始响应对象(并将传递给下一个渲染后回调等)

SimpleTemplateResponse.render()

response.content 设置为 SimpleTemplateResponse.rendered_content 获得的结果,运行所有渲染后回调,并返回结果响应对象。

render() 只会在第一次被调用时产生效果。 在后续调用中,它将返回从第一次调用中获得的结果。


TemplateResponse 物体

class TemplateResponse
TemplateResponseSimpleTemplateResponse 的子类,它知道当前的 HttpRequest

方法

TemplateResponse.__init__(request, template, context=None, content_type=None, status=None, charset=None, using=None)
使用给定的请求、模板、上下文、内容类型、HTTP 状态和字符集实例化 TemplateResponse 对象。
request
HttpRequest 实例。
template
依赖于后端的模板对象(例如由 get_template() 返回的对象)、模板名称或模板名称列表。
context
要添加到模板上下文的 dict 值。 默认情况下,这是一个空字典。
content_type
HTTP Content-Type 标头中包含的值,包括 MIME 类型规范和字符集编码。 如果指定了 content_type,则使用其值。 否则,使用 'text/html'
status
响应的 HTTP 状态代码。
charset
响应将在其中编码的字符集。 如果没有给出,它将从 content_type 中提取,如果不成功,将使用 :setting:`DEFAULT_CHARSET` 设置。
using
:setting:`名称 ` 用于加载模板的模板引擎。


渲染过程

在将 TemplateResponse 实例返回给客户端之前,它必须被渲染。 渲染过程采用模板和上下文的中间表示,并将其转换为可以提供给客户端的最终字节流。

TemplateResponse 在三种情况下会被渲染:

  • TemplateResponse 实例被显式渲染时,使用 SimpleTemplateResponse.render() 方法。
  • 通过分配response.content明确设置响应的内容时。
  • 在通过模板响应中间件之后,但在通过响应中间件之前。

TemplateResponse 只能渲染一次。 第一次调用 SimpleTemplateResponse.render() 设置响应的内容; 后续渲染调用不会更改响应内容。

但是,当显式分配 response.content 时,将始终应用更改。 如果要强制重新渲染内容,可以重新评估渲染的内容,并手动分配响应的内容:

# Set up a rendered TemplateResponse
>>> from django.template.response import TemplateResponse
>>> t = TemplateResponse(request, 'original.html', {})
>>> t.render()
>>> print(t.content)
Original content

# Re-rendering doesn't change content
>>> t.template_name = 'new.html'
>>> t.render()
>>> print(t.content)
Original content

# Assigning content does change, no render() call required
>>> t.content = t.rendered_content
>>> print(t.content)
New content

渲染后回调

某些操作(例如缓存)无法在未渲染的模板上执行。 它们必须在完全完整且呈现的响应上执行。

如果您使用的是中间件,则可以这样做。 中间件提供了多种机会来处理退出视图时的响应。 如果您将行为放在响应中间件中,则保证在模板渲染发生后执行。

但是,如果您使用装饰器,则不存在相同的机会。 装饰器中定义的任何行为都会立即处理。

为了弥补这一点(以及任何其他类似的用例),TemplateResponse 允许您注册将在渲染完成时调用的回调。 使用此回调,您可以将关键处理推迟到可以保证呈现的内容可用的时间点。

要定义渲染后回调,请定义一个接受单个参数(响应)的函数,并将该函数注册到模板响应:

from django.template.response import TemplateResponse

def my_render_callback(response):
    # Do content-sensitive processing
    do_post_processing()

def my_view(request):
    # Create a response
    response = TemplateResponse(request, 'mytemplate.html', {})
    # Register the callback
    response.add_post_render_callback(my_render_callback)
    # Return the response
    return response

my_render_callback() 将在 mytemplate.html 渲染后调用,并将提供完全渲染的 TemplateResponse 实例作为参数。

如果模板已经被渲染,回调将被立即调用。


使用 TemplateResponse 和 SimpleTemplateResponse

TemplateResponse 对象可以在任何可以使用普通 django.http.HttpResponse 的地方使用。 它也可以用作调用 render() 的替代方法。

例如,以下视图返回带有模板和包含查询集的上下文的 TemplateResponse

from django.template.response import TemplateResponse

def blog_index(request):
    return TemplateResponse(request, 'entry_list.html', {'entries': Entry.objects.all()})