shortcuts.txt 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. =========================
  2. Django shortcut functions
  3. =========================
  4. .. module:: django.shortcuts
  5. :synopsis:
  6. Convenience shortcuts that span multiple levels of Django's MVC stack.
  7. .. index:: shortcuts
  8. The package ``django.shortcuts`` collects helper functions and classes that
  9. "span" multiple levels of MVC. In other words, these functions/classes
  10. introduce controlled coupling for convenience's sake.
  11. ``render``
  12. ==========
  13. .. function:: render(request, template_name[, dictionary][, context_instance][, content_type][, status][, current_app])
  14. Combines a given template with a given context dictionary and returns an
  15. :class:`~django.http.HttpResponse` object with that rendered text.
  16. :func:`render()` is the same as a call to
  17. :func:`render_to_response()` with a `context_instance` argument that
  18. forces the use of a :class:`~django.template.RequestContext`.
  19. Required arguments
  20. ------------------
  21. ``request``
  22. The request object used to generate this response.
  23. ``template_name``
  24. The full name of a template to use or sequence of template names.
  25. Optional arguments
  26. ------------------
  27. ``dictionary``
  28. A dictionary of values to add to the template context. By default, this
  29. is an empty dictionary. If a value in the dictionary is callable, the
  30. view will call it just before rendering the template.
  31. ``context_instance``
  32. The context instance to render the template with. By default, the template
  33. will be rendered with a ``RequestContext`` instance (filled with values from
  34. ``request`` and ``dictionary``).
  35. ``content_type``
  36. The MIME type to use for the resulting document. Defaults to the value of
  37. the :setting:`DEFAULT_CONTENT_TYPE` setting.
  38. .. versionchanged:: 1.5
  39. This parameter used to be called ``mimetype``.
  40. ``status``
  41. The status code for the response. Defaults to ``200``.
  42. ``current_app``
  43. A hint indicating which application contains the current view. See the
  44. :ref:`namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`
  45. for more information.
  46. Example
  47. -------
  48. The following example renders the template ``myapp/index.html`` with the
  49. MIME type :mimetype:`application/xhtml+xml`::
  50. from django.shortcuts import render
  51. def my_view(request):
  52. # View code here...
  53. return render(request, 'myapp/index.html', {"foo": "bar"},
  54. content_type="application/xhtml+xml")
  55. This example is equivalent to::
  56. from django.http import HttpResponse
  57. from django.template import RequestContext, loader
  58. def my_view(request):
  59. # View code here...
  60. t = loader.get_template('myapp/template.html')
  61. c = RequestContext(request, {'foo': 'bar'})
  62. return HttpResponse(t.render(c),
  63. content_type="application/xhtml+xml")
  64. ``render_to_response``
  65. ======================
  66. .. function:: render_to_response(template_name[, dictionary][, context_instance][, content_type])
  67. Renders a given template with a given context dictionary and returns an
  68. :class:`~django.http.HttpResponse` object with that rendered text.
  69. Required arguments
  70. ------------------
  71. ``template_name``
  72. The full name of a template to use or sequence of template names. If a
  73. sequence is given, the first template that exists will be used. See the
  74. :ref:`template loader documentation <ref-templates-api-the-python-api>`
  75. for more information on how templates are found.
  76. Optional arguments
  77. ------------------
  78. ``dictionary``
  79. A dictionary of values to add to the template context. By default, this
  80. is an empty dictionary. If a value in the dictionary is callable, the
  81. view will call it just before rendering the template.
  82. ``context_instance``
  83. The context instance to render the template with. By default, the template
  84. will be rendered with a :class:`~django.template.Context` instance (filled
  85. with values from ``dictionary``). If you need to use :ref:`context
  86. processors <subclassing-context-requestcontext>`, render the template with
  87. a :class:`~django.template.RequestContext` instance instead. Your code
  88. might look something like this::
  89. return render_to_response('my_template.html',
  90. my_data_dictionary,
  91. context_instance=RequestContext(request))
  92. ``content_type``
  93. The MIME type to use for the resulting document. Defaults to the value of
  94. the :setting:`DEFAULT_CONTENT_TYPE` setting.
  95. .. versionchanged:: 1.5
  96. This parameter used to be called ``mimetype``.
  97. Example
  98. -------
  99. The following example renders the template ``myapp/index.html`` with the
  100. MIME type :mimetype:`application/xhtml+xml`::
  101. from django.shortcuts import render_to_response
  102. def my_view(request):
  103. # View code here...
  104. return render_to_response('myapp/index.html', {"foo": "bar"},
  105. mimetype="application/xhtml+xml")
  106. This example is equivalent to::
  107. from django.http import HttpResponse
  108. from django.template import Context, loader
  109. def my_view(request):
  110. # View code here...
  111. t = loader.get_template('myapp/template.html')
  112. c = Context({'foo': 'bar'})
  113. return HttpResponse(t.render(c),
  114. content_type="application/xhtml+xml")
  115. ``redirect``
  116. ============
  117. .. function:: redirect(to[, permanent=False], *args, **kwargs)
  118. Returns an :class:`~django.http.HttpResponseRedirect` to the appropriate URL
  119. for the arguments passed.
  120. The arguments could be:
  121. * A model: the model's `get_absolute_url()` function will be called.
  122. * A view name, possibly with arguments: `urlresolvers.reverse()` will
  123. be used to reverse-resolve the name.
  124. * A URL, which will be used as-is for the redirect location.
  125. By default issues a temporary redirect; pass ``permanent=True`` to issue a
  126. permanent redirect
  127. Examples
  128. --------
  129. You can use the :func:`redirect` function in a number of ways.
  130. 1. By passing some object; that object's
  131. :meth:`~django.db.models.Model.get_absolute_url` method will be called
  132. to figure out the redirect URL::
  133. from django.shortcuts import redirect
  134. def my_view(request):
  135. ...
  136. object = MyModel.objects.get(...)
  137. return redirect(object)
  138. 2. By passing the name of a view and optionally some positional or
  139. keyword arguments; the URL will be reverse resolved using the
  140. :func:`~django.core.urlresolvers.reverse` method::
  141. def my_view(request):
  142. ...
  143. return redirect('some-view-name', foo='bar')
  144. 3. By passing a hardcoded URL to redirect to::
  145. def my_view(request):
  146. ...
  147. return redirect('/some/url/')
  148. This also works with full URLs::
  149. def my_view(request):
  150. ...
  151. return redirect('http://example.com/')
  152. By default, :func:`redirect` returns a temporary redirect. All of the above
  153. forms accept a ``permanent`` argument; if set to ``True`` a permanent redirect
  154. will be returned::
  155. def my_view(request):
  156. ...
  157. object = MyModel.objects.get(...)
  158. return redirect(object, permanent=True)
  159. ``get_object_or_404``
  160. =====================
  161. .. function:: get_object_or_404(klass, *args, **kwargs)
  162. Calls :meth:`~django.db.models.query.QuerySet.get()` on a given model manager,
  163. but it raises :class:`~django.http.Http404` instead of the model's
  164. :class:`~django.core.exceptions.DoesNotExist` exception.
  165. Required arguments
  166. ------------------
  167. ``klass``
  168. A :class:`~django.db.models.Model`, :class:`~django.db.models.Manager` or
  169. :class:`~django.db.models.query.QuerySet` instance from which to get the
  170. object.
  171. ``**kwargs``
  172. Lookup parameters, which should be in the format accepted by ``get()`` and
  173. ``filter()``.
  174. Example
  175. -------
  176. The following example gets the object with the primary key of 1 from
  177. ``MyModel``::
  178. from django.shortcuts import get_object_or_404
  179. def my_view(request):
  180. my_object = get_object_or_404(MyModel, pk=1)
  181. This example is equivalent to::
  182. from django.http import Http404
  183. def my_view(request):
  184. try:
  185. my_object = MyModel.objects.get(pk=1)
  186. except MyModel.DoesNotExist:
  187. raise Http404
  188. Note: As with ``get()``, a
  189. :class:`~django.core.exceptions.MultipleObjectsReturned` exception
  190. will be raised if more than one object is found.
  191. ``get_list_or_404``
  192. ===================
  193. .. function:: get_list_or_404(klass, *args, **kwargs)
  194. Returns the result of :meth:`~django.db.models.query.QuerySet.filter()` on a
  195. given model manager, raising :class:`~django.http.Http404` if the resulting
  196. list is empty.
  197. Required arguments
  198. ------------------
  199. ``klass``
  200. A :class:`~django.db.models.Model`, :class:`~django.db.models.Manager` or
  201. :class:`~django.db.models.query.QuerySet` instance from which to get the
  202. list.
  203. ``**kwargs``
  204. Lookup parameters, which should be in the format accepted by ``get()`` and
  205. ``filter()``.
  206. Example
  207. -------
  208. The following example gets all published objects from ``MyModel``::
  209. from django.shortcuts import get_list_or_404
  210. def my_view(request):
  211. my_objects = get_list_or_404(MyModel, published=True)
  212. This example is equivalent to::
  213. from django.http import Http404
  214. def my_view(request):
  215. my_objects = list(MyModel.objects.filter(published=True))
  216. if not my_objects:
  217. raise Http404