shortcuts.txt 9.1 KB

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