template-response.txt 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. ===========================================
  2. TemplateResponse and SimpleTemplateResponse
  3. ===========================================
  4. .. module:: django.template.response
  5. :synopsis: Classes dealing with lazy-rendered HTTP responses.
  6. Standard :class:`~django.http.HttpResponse` objects are static structures.
  7. They are provided with a block of pre-rendered content at time of
  8. construction, and while that content can be modified, it isn't in a form that
  9. makes it easy to perform modifications.
  10. However, it can sometimes be beneficial to allow decorators or
  11. middleware to modify a response *after* it has been constructed by the
  12. view. For example, you may want to change the template that is used,
  13. or put additional data into the context.
  14. TemplateResponse provides a way to do just that. Unlike basic
  15. :class:`~django.http.HttpResponse` objects, TemplateResponse objects retain
  16. the details of the template and context that was provided by the view to
  17. compute the response. The final output of the response is not computed until
  18. it is needed, later in the response process.
  19. SimpleTemplateResponse objects
  20. ==============================
  21. .. class:: SimpleTemplateResponse()
  22. Attributes
  23. ----------
  24. .. attribute:: SimpleTemplateResponse.template_name
  25. The name of the template to be rendered. Accepts a
  26. :class:`~django.template.Template` object, a path to a template or list
  27. of template paths.
  28. Example: ``['foo.html', 'path/to/bar.html']``
  29. .. attribute:: SimpleTemplateResponse.context_data
  30. The context data to be used when rendering the template. It can be
  31. a dictionary or a context object.
  32. Example: ``{'foo': 123}``
  33. .. attribute:: SimpleTemplateResponse.rendered_content
  34. The current rendered value of the response content, using the current
  35. template and context data.
  36. .. attribute:: SimpleTemplateResponse.is_rendered
  37. A boolean indicating whether the response content has been rendered.
  38. Methods
  39. -------
  40. .. method:: SimpleTemplateResponse.__init__(template, context=None, content_type=None, status=None, charset=None)
  41. Instantiates a
  42. :class:`~django.template.response.SimpleTemplateResponse` object
  43. with the given template, context, content type, and HTTP status.
  44. ``template``
  45. The full name of a template, or a sequence of template names.
  46. :class:`~django.template.Template` instances can also be used.
  47. ``context``
  48. A dictionary of values to add to the template context. By default,
  49. this is an empty dictionary. :class:`~django.template.Context` objects
  50. are also accepted as ``context`` values.
  51. ``status``
  52. The HTTP Status code for the response.
  53. ``content_type``
  54. The value included in the HTTP ``Content-Type`` header, including the
  55. MIME type specification and the character set encoding. If
  56. ``content_type`` is specified, then its value is used. Otherwise,
  57. :setting:`DEFAULT_CONTENT_TYPE` is used.
  58. ``charset``
  59. The charset in which the response will be encoded. If not given it will
  60. be extracted from ``content_type``, and if that is unsuccessful, the
  61. :setting:`DEFAULT_CHARSET` setting will be used.
  62. .. versionadded:: 1.8
  63. The ``charset`` parameter was added.
  64. .. method:: SimpleTemplateResponse.resolve_context(context)
  65. Converts context data into a context instance that can be used for
  66. rendering a template. Accepts a dictionary of context data or a
  67. context object. Returns a :class:`~django.template.Context`
  68. instance containing the provided data.
  69. Override this method in order to customize context instantiation.
  70. .. method:: SimpleTemplateResponse.resolve_template(template)
  71. Resolves the template instance to use for rendering. Accepts a
  72. path of a template to use, or a sequence of template paths.
  73. :class:`~django.template.Template` instances may also be provided.
  74. Returns the :class:`~django.template.Template` instance to be
  75. rendered.
  76. Override this method in order to customize template rendering.
  77. .. method:: SimpleTemplateResponse.add_post_render_callback()
  78. Add a callback that will be invoked after rendering has taken
  79. place. This hook can be used to defer certain processing
  80. operations (such as caching) until after rendering has occurred.
  81. If the :class:`~django.template.response.SimpleTemplateResponse`
  82. has already been rendered, the callback will be invoked
  83. immediately.
  84. When called, callbacks will be passed a single argument -- the
  85. rendered :class:`~django.template.response.SimpleTemplateResponse`
  86. instance.
  87. If the callback returns a value that is not ``None``, this will be
  88. used as the response instead of the original response object (and
  89. will be passed to the next post rendering callback etc.)
  90. .. method:: SimpleTemplateResponse.render()
  91. Sets ``response.content`` to the result obtained by
  92. :attr:`SimpleTemplateResponse.rendered_content`, runs all post-rendering
  93. callbacks, and returns the resulting response object.
  94. ``render()`` will only have an effect the first time it is called. On
  95. subsequent calls, it will return the result obtained from the first call.
  96. TemplateResponse objects
  97. ========================
  98. .. class:: TemplateResponse()
  99. ``TemplateResponse`` is a subclass of
  100. :class:`~django.template.response.SimpleTemplateResponse` that uses
  101. a :class:`~django.template.RequestContext` instead of
  102. a :class:`~django.template.Context`.
  103. Methods
  104. -------
  105. .. method:: TemplateResponse.__init__(request, template, context=None, content_type=None, status=None, current_app=None, charset=None)
  106. Instantiates an ``TemplateResponse`` object with the given
  107. template, context, MIME type and HTTP status.
  108. ``request``
  109. An :class:`~django.http.HttpRequest` instance.
  110. ``template``
  111. The full name of a template, or a sequence of template names.
  112. :class:`~django.template.Template` instances can also be used.
  113. ``context``
  114. A dictionary of values to add to the template context. By default,
  115. this is an empty dictionary. :class:`~django.template.Context` objects
  116. are also accepted as ``context`` values. If you pass a
  117. :class:`~django.template.Context` instance or subclass, it will be used
  118. instead of creating a new :class:`~django.template.RequestContext`.
  119. ``status``
  120. The HTTP Status code for the response.
  121. ``content_type``
  122. The value included in the HTTP ``Content-Type`` header, including the
  123. MIME type specification and the character set encoding. If
  124. ``content_type`` is specified, then its value is used. Otherwise,
  125. :setting:`DEFAULT_CONTENT_TYPE` is used.
  126. ``current_app``
  127. A hint indicating which application contains the current view. See the
  128. :ref:`namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`
  129. for more information.
  130. ``charset``
  131. The charset in which the response will be encoded. If not given it will
  132. be extracted from ``content_type``, and if that is unsuccessful, the
  133. :setting:`DEFAULT_CHARSET` setting will be used.
  134. .. versionadded:: 1.8
  135. The ``charset`` parameter was added.
  136. The rendering process
  137. =====================
  138. Before a :class:`~django.template.response.TemplateResponse` instance can be
  139. returned to the client, it must be rendered. The rendering process takes the
  140. intermediate representation of template and context, and turns it into the
  141. final byte stream that can be served to the client.
  142. There are three circumstances under which a ``TemplateResponse`` will be
  143. rendered:
  144. * When the ``TemplateResponse`` instance is explicitly rendered, using
  145. the :meth:`SimpleTemplateResponse.render()` method.
  146. * When the content of the response is explicitly set by assigning
  147. ``response.content``.
  148. * After passing through template response middleware, but before
  149. passing through response middleware.
  150. A ``TemplateResponse`` can only be rendered once. The first call to
  151. :meth:`SimpleTemplateResponse.render` sets the content of the response;
  152. subsequent rendering calls do not change the response content.
  153. However, when ``response.content`` is explicitly assigned, the
  154. change is always applied. If you want to force the content to be
  155. re-rendered, you can re-evaluate the rendered content, and assign
  156. the content of the response manually::
  157. # Set up a rendered TemplateResponse
  158. >>> from django.template.response import TemplateResponse
  159. >>> t = TemplateResponse(request, 'original.html', {})
  160. >>> t.render()
  161. >>> print(t.content)
  162. Original content
  163. # Re-rendering doesn't change content
  164. >>> t.template_name = 'new.html'
  165. >>> t.render()
  166. >>> print(t.content)
  167. Original content
  168. # Assigning content does change, no render() call required
  169. >>> t.content = t.rendered_content
  170. >>> print(t.content)
  171. New content
  172. Post-render callbacks
  173. ---------------------
  174. Some operations -- such as caching -- cannot be performed on an
  175. unrendered template. They must be performed on a fully complete and
  176. rendered response.
  177. If you're using middleware, the solution is easy. Middleware provides
  178. multiple opportunities to process a response on exit from a view. If
  179. you put behavior in the Response middleware is guaranteed to execute
  180. after template rendering has taken place.
  181. However, if you're using a decorator, the same opportunities do not
  182. exist. Any behavior defined in a decorator is handled immediately.
  183. To compensate for this (and any other analogous use cases),
  184. :class:`TemplateResponse` allows you to register callbacks that will
  185. be invoked when rendering has completed. Using this callback, you can
  186. defer critical processing until a point where you can guarantee that
  187. rendered content will be available.
  188. To define a post-render callback, just define a function that takes
  189. a single argument -- response -- and register that function with
  190. the template response::
  191. from django.template.response import TemplateResponse
  192. def my_render_callback(response):
  193. # Do content-sensitive processing
  194. do_post_processing()
  195. def my_view(request):
  196. # Create a response
  197. response = TemplateResponse(request, 'mytemplate.html', {})
  198. # Register the callback
  199. response.add_post_render_callback(my_render_callback)
  200. # Return the response
  201. return response
  202. ``my_render_callback()`` will be invoked after the ``mytemplate.html``
  203. has been rendered, and will be provided the fully rendered
  204. :class:`TemplateResponse` instance as an argument.
  205. If the template has already been rendered, the callback will be
  206. invoked immediately.
  207. Using TemplateResponse and SimpleTemplateResponse
  208. =================================================
  209. A TemplateResponse object can be used anywhere that a normal HttpResponse can be
  210. used. It can also be used as an alternative to calling
  211. :func:`~django.shortcuts.render()` or
  212. :func:`~django.shortcuts.render_to_response()`.
  213. For example, the following simple view returns a
  214. :class:`TemplateResponse()` with a simple template, and a context
  215. containing a queryset::
  216. from django.template.response import TemplateResponse
  217. def blog_index(request):
  218. return TemplateResponse(request, 'entry_list.html', {'entries': Entry.objects.all()})