template-response.txt 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. ===========================================
  2. TemplateResponse and SimpleTemplateResponse
  3. ===========================================
  4. .. versionadded:: 1.3
  5. .. module:: django.template.response
  6. :synopsis: Classes dealing with lazy-rendered HTTP responses.
  7. Standard HttpResponse objects are static structures. They are provided
  8. with a block of pre-rendered content at time of construction, and
  9. while that content can be modified, it isn't in a form that makes it
  10. easy to perform modifications.
  11. However, it can sometimes be beneficial to allow decorators or
  12. middleware to modify a response *after* it has been constructed by the
  13. view. For example, you may want to change the template that is used,
  14. or put additional data into the context.
  15. TemplateResponse provides a way to do just that. Unlike basic
  16. HttpResponse objects, TemplateResponse objects retain the details of
  17. the template and context that was provided by the view to compute the
  18. response. The final output of the response is not computed until
  19. it is needed, later in the response process.
  20. TemplateResponse objects
  21. ========================
  22. .. class:: SimpleTemplateResponse()
  23. Attributes
  24. ----------
  25. .. attribute:: SimpleTemplateResponse.template_name
  26. The name of the template to be rendered. Accepts
  27. :class:`django.template.Template` object, path to template or list
  28. of paths.
  29. Example: ``['foo.html', 'path/to/bar.html']``
  30. .. attribute:: SimpleTemplateResponse.context_data
  31. The context data to be used when rendering the template. It can be
  32. a dictionary or a context object.
  33. Example: ``{'foo': 123}``
  34. .. attr:: SimpleTemplateResponse.rendered_content:
  35. The current rendered value of the response content, using the current
  36. template and context data.
  37. .. attr:: SimpleTemplateResponse.is_rendered:
  38. A boolean indicating whether the response content has been rendered.
  39. Methods
  40. -------
  41. .. method:: SimpleTemplateResponse.__init__(template, context=None, mimetype=None, status=None, content_type=None)
  42. Instantiates an
  43. :class:`~django.template.response.SimpleTemplateResponse` object
  44. with the given template, context, MIME type and HTTP status.
  45. ``template`` is a full name of a template, or a sequence of
  46. template names. :class:`django.template.Template` instances can
  47. also be used.
  48. ``context`` is a dictionary of values to add to the template
  49. context. By default, this is an empty dictionary.
  50. :class:`~django.template.Context` objects are also accepted as
  51. ``context`` values.
  52. ``status`` is the HTTP Status code for the response.
  53. ``content_type`` is an alias for ``mimetype``. Historically, this
  54. parameter was only called ``mimetype``, but since this is actually
  55. the value included in the HTTP ``Content-Type`` header, it can
  56. also include the character set encoding, which makes it more than
  57. just a MIME type specification. If ``mimetype`` is specified (not
  58. ``None``), that value is used. Otherwise, ``content_type`` is
  59. used. If neither is given, the ``DEFAULT_CONTENT_TYPE`` setting is
  60. used.
  61. .. method:: SimpleTemplateResponse.resolve_context(context)
  62. Converts context data into a context instance that can be used for
  63. rendering a template. Accepts a dictionary of context data or a
  64. context object. Returns a :class:`~django.template.Context`
  65. instance containing the provided data.
  66. Override this method in order to customize context instantiation.
  67. .. method:: SimpleTemplateResponse.resolve_template(template)
  68. Resolves the template instance to use for rendering. Accepts a
  69. path of a template to use, or a sequence of template paths.
  70. :class:`~django.template.Template` instances may also be provided.
  71. Returns the :class:`~django.template.Template` instance to be
  72. rendered.
  73. Override this method in order to customize template rendering.
  74. .. method:: SimpleTemplateResponse.render():
  75. Sets :attr:`response.content` to the result obtained by
  76. :attr:`SimpleTemplateResponse.rendered_content`.
  77. :meth:`~SimpleTemplateResponse.render()` will only have an effect
  78. the first time it is called. On subsequent calls, it will return
  79. the result obtained from the first call.
  80. .. class:: TemplateResponse()
  81. TemplateResponse is a subclass of :class:`SimpleTemplateResponse
  82. <django.template.response.SimpleTemplateResponse>` that uses
  83. RequestContext instead of Context.
  84. .. method:: TemplateResponse.__init__(request, template, context=None, mimetype=None, status=None, content_type=None)
  85. Instantiates an ``TemplateResponse`` object with the given
  86. template, context, MIME type and HTTP status.
  87. ``request`` is a HttpRequest instance.
  88. ``template`` is a full name of a template to use or sequence of
  89. template names. :class:`django.template.Template` instances are
  90. also accepted.
  91. ``context`` is a dictionary of values to add to the template
  92. context. By default, this is an empty dictionary; context objects
  93. are also accepted as ``context`` values.
  94. ``status`` is the HTTP Status code for the response.
  95. ``content_type`` is an alias for ``mimetype``. Historically, this
  96. parameter was only called ``mimetype``, but since this is actually
  97. the value included in the HTTP ``Content-Type`` header, it can also
  98. include the character set encoding, which makes it more than just a
  99. MIME type specification. If ``mimetype`` is specified (not
  100. ``None``), that value is used. Otherwise, ``content_type`` is used.
  101. If neither is given, the ``DEFAULT_CONTENT_TYPE`` setting is used.
  102. The rendering process
  103. =====================
  104. Before a :class:`TemplateResponse()` instance can be returned to the
  105. client, it must be rendered. The rendering process takes the
  106. intermediate representation of template and context, and turns it into
  107. the final byte stream that can be served to the client.
  108. There are three circumstances under which a TemplateResponse will be
  109. rendered:
  110. * When the TemplateResponse instance is explicitly rendered, using
  111. the :meth:`SimpleTemplateResponse.render()` method.
  112. * When the content of the response is explicitly set by assigning
  113. :attr:`response.content`.
  114. * After passing through template response middleware, but before
  115. passing through response middleware.
  116. A TemplateResponse can only be rendered once. The first call to
  117. :meth:`SimpleTemplateResponse.render()` sets the content of the
  118. response; subsequent rendering calls do not change the response
  119. content.
  120. However, when :attr:`response.content` is explicitly assigned, the
  121. change is always applied. If you want to force the content to be
  122. re-rendered, you can re-evaluate the rendered content, and assign
  123. the content of the response manually::
  124. # Set up a baked TemplateResponse
  125. >>> t = TemplateResponse(request, 'original.html', {})
  126. >>> t.render()
  127. >>> print t.content
  128. Original content
  129. # Rebaking doesn't change content
  130. >>> t.template_name = 'new.html'
  131. >>> t.render()
  132. >>> print t.content
  133. Original content
  134. # Assigning content does change, no render() call required
  135. >>> t.content = t.rendered_content
  136. >>> print t.content
  137. New content
  138. Using TemplateResponse and SimpleTemplateResponse
  139. =================================================
  140. A TemplateResponse object can be used anywhere that a normal
  141. HttpResponse can be used. It can also be used as an alternative to
  142. calling :method:`~django.shortcuts.render_to_response()`.
  143. For example, the following simple view returns a
  144. :class:`TemplateResponse()` with a simple template, and a context
  145. containing a queryset::
  146. from django.template.response import TemplateResponse
  147. def blog_index(request):
  148. return TemplateResponse(request, 'entry_list.html', {'entries': Entry.objects.all()})