shortcuts.txt 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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[, context][, context_instance][, content_type][, status][, current_app][, dirs])
  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. Django does not provide a shortcut function which returns a
  20. :class:`~django.template.response.TemplateResponse` because the constructor
  21. of :class:`~django.template.response.TemplateResponse` offers the same level
  22. of convenience as :func:`render()`.
  23. Required arguments
  24. ------------------
  25. ``request``
  26. The request object used to generate this response.
  27. ``template_name``
  28. The full name of a template to use or sequence of template names.
  29. Optional arguments
  30. ------------------
  31. ``context``
  32. A dictionary of values to add to the template context. By default, this
  33. is an empty dictionary. If a value in the dictionary is callable, the
  34. view will call it just before rendering the template.
  35. .. versionchanged:: 1.8
  36. The ``context`` argument used to be called ``dictionary``. That name
  37. is deprecated in Django 1.8 and will be removed in Django 2.0.
  38. ``context_instance``
  39. The context instance to render the template with. By default, the template
  40. will be rendered with a ``RequestContext`` instance (filled with values from
  41. ``request`` and ``context``).
  42. .. deprecated:: 1.8
  43. The ``context_instance`` argument is deprecated. Simply use ``context``.
  44. ``content_type``
  45. The MIME type to use for the resulting document. Defaults to the value of
  46. the :setting:`DEFAULT_CONTENT_TYPE` setting.
  47. ``status``
  48. The status code for the response. Defaults to ``200``.
  49. ``current_app``
  50. A hint indicating which application contains the current view. See the
  51. :ref:`namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`
  52. for more information.
  53. .. versionchanged:: 1.7
  54. The ``dirs`` parameter was added.
  55. .. deprecated:: 1.8
  56. The ``dirs`` parameter was deprecated.
  57. Example
  58. -------
  59. The following example renders the template ``myapp/index.html`` with the
  60. MIME type :mimetype:`application/xhtml+xml`::
  61. from django.shortcuts import render
  62. def my_view(request):
  63. # View code here...
  64. return render(request, 'myapp/index.html', {"foo": "bar"},
  65. content_type="application/xhtml+xml")
  66. This example is equivalent to::
  67. from django.http import HttpResponse
  68. from django.template import RequestContext, loader
  69. def my_view(request):
  70. # View code here...
  71. t = loader.get_template('myapp/index.html')
  72. c = RequestContext(request, {'foo': 'bar'})
  73. return HttpResponse(t.render(c),
  74. content_type="application/xhtml+xml")
  75. ``render_to_response``
  76. ======================
  77. .. function:: render_to_response(template_name[, context][, context_instance][, content_type][, status][, dirs])
  78. Renders a given template with a given context dictionary and returns an
  79. :class:`~django.http.HttpResponse` object with that rendered text.
  80. Required arguments
  81. ------------------
  82. ``template_name``
  83. The full name of a template to use or sequence of template names. If a
  84. sequence is given, the first template that exists will be used. See the
  85. :ref:`template loader documentation <ref-templates-api-the-python-api>`
  86. for more information on how templates are found.
  87. Optional arguments
  88. ------------------
  89. ``context``
  90. A dictionary of values to add to the template context. By default, this
  91. is an empty dictionary. If a value in the dictionary is callable, the
  92. view will call it just before rendering the template.
  93. .. versionchanged:: 1.8
  94. The ``context`` argument used to be called ``dictionary``. That name
  95. is deprecated in Django 1.8 and will be removed in Django 2.0.
  96. ``context_instance``
  97. The context instance to render the template with. By default, the template
  98. will be rendered with a :class:`~django.template.Context` instance (filled
  99. with values from ``context``). If you need to use :ref:`context
  100. processors <subclassing-context-requestcontext>`, render the template with
  101. a :class:`~django.template.RequestContext` instance instead. Your code
  102. might look something like this::
  103. return render_to_response('my_template.html',
  104. my_context,
  105. context_instance=RequestContext(request))
  106. .. deprecated:: 1.8
  107. The ``context_instance`` argument is deprecated. Simply use ``context``.
  108. ``content_type``
  109. The MIME type to use for the resulting document. Defaults to the value of
  110. the :setting:`DEFAULT_CONTENT_TYPE` setting.
  111. ``status``
  112. The status code for the response. Defaults to ``200``.
  113. .. versionchanged:: 1.8
  114. The ``status`` parameter was added.
  115. .. versionchanged:: 1.7
  116. The ``dirs`` parameter was added.
  117. .. deprecated:: 1.8
  118. The ``dirs`` parameter was deprecated.
  119. Example
  120. -------
  121. The following example renders the template ``myapp/index.html`` with the
  122. MIME type :mimetype:`application/xhtml+xml`::
  123. from django.shortcuts import render_to_response
  124. def my_view(request):
  125. # View code here...
  126. return render_to_response('myapp/index.html', {"foo": "bar"},
  127. content_type="application/xhtml+xml")
  128. This example is equivalent to::
  129. from django.http import HttpResponse
  130. from django.template import Context, loader
  131. def my_view(request):
  132. # View code here...
  133. t = loader.get_template('myapp/index.html')
  134. c = Context({'foo': 'bar'})
  135. return HttpResponse(t.render(c),
  136. content_type="application/xhtml+xml")
  137. ``redirect``
  138. ============
  139. .. function:: redirect(to[, permanent=False], *args, **kwargs)
  140. Returns an :class:`~django.http.HttpResponseRedirect` to the appropriate URL
  141. for the arguments passed.
  142. The arguments could be:
  143. * A model: the model's :meth:`~django.db.models.Model.get_absolute_url()`
  144. function will be called.
  145. * A view name, possibly with arguments: :func:`urlresolvers.reverse
  146. <django.core.urlresolvers.reverse>` will be used to reverse-resolve the
  147. name.
  148. * An absolute or relative URL, which will be used as-is for the redirect
  149. location.
  150. By default issues a temporary redirect; pass ``permanent=True`` to issue a
  151. permanent redirect.
  152. .. versionchanged:: 1.7
  153. The ability to use relative URLs was added.
  154. Examples
  155. --------
  156. You can use the :func:`redirect` function in a number of ways.
  157. 1. By passing some object; that object's
  158. :meth:`~django.db.models.Model.get_absolute_url` method will be called
  159. to figure out the redirect URL::
  160. from django.shortcuts import redirect
  161. def my_view(request):
  162. ...
  163. object = MyModel.objects.get(...)
  164. return redirect(object)
  165. 2. By passing the name of a view and optionally some positional or
  166. keyword arguments; the URL will be reverse resolved using the
  167. :func:`~django.core.urlresolvers.reverse` method::
  168. def my_view(request):
  169. ...
  170. return redirect('some-view-name', foo='bar')
  171. 3. By passing a hardcoded URL to redirect to::
  172. def my_view(request):
  173. ...
  174. return redirect('/some/url/')
  175. This also works with full URLs::
  176. def my_view(request):
  177. ...
  178. return redirect('http://example.com/')
  179. By default, :func:`redirect` returns a temporary redirect. All of the above
  180. forms accept a ``permanent`` argument; if set to ``True`` a permanent redirect
  181. will be returned::
  182. def my_view(request):
  183. ...
  184. object = MyModel.objects.get(...)
  185. return redirect(object, permanent=True)
  186. ``get_object_or_404``
  187. =====================
  188. .. function:: get_object_or_404(klass, *args, **kwargs)
  189. Calls :meth:`~django.db.models.query.QuerySet.get()` on a given model manager,
  190. but it raises :class:`~django.http.Http404` instead of the model's
  191. :class:`~django.core.exceptions.DoesNotExist` exception.
  192. Required arguments
  193. ------------------
  194. ``klass``
  195. A :class:`~django.db.models.Model` class,
  196. a :class:`~django.db.models.Manager`,
  197. or a :class:`~django.db.models.query.QuerySet` instance from which to get
  198. the object.
  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 the object with the primary key of 1 from
  205. ``MyModel``::
  206. from django.shortcuts import get_object_or_404
  207. def my_view(request):
  208. my_object = get_object_or_404(MyModel, pk=1)
  209. This example is equivalent to::
  210. from django.http import Http404
  211. def my_view(request):
  212. try:
  213. my_object = MyModel.objects.get(pk=1)
  214. except MyModel.DoesNotExist:
  215. raise Http404
  216. The most common use case is to pass a :class:`~django.db.models.Model`, as
  217. shown above. However, you can also pass a
  218. :class:`~django.db.models.query.QuerySet` instance::
  219. queryset = Book.objects.filter(title__startswith='M')
  220. get_object_or_404(queryset, pk=1)
  221. The above example is a bit contrived since it's equivalent to doing::
  222. get_object_or_404(Book, title__startswith='M', pk=1)
  223. but it can be useful if you are passed the ``queryset`` variable from somewhere
  224. else.
  225. Finally, you can also use a :class:`~django.db.models.Manager`. This is useful
  226. for example if you have a
  227. :ref:`custom manager<custom-managers>`::
  228. get_object_or_404(Book.dahl_objects, title='Matilda')
  229. You can also use
  230. :class:`related managers<django.db.models.fields.related.RelatedManager>`::
  231. author = Author.objects.get(name='Roald Dahl')
  232. get_object_or_404(author.book_set, title='Matilda')
  233. Note: As with ``get()``, a
  234. :class:`~django.core.exceptions.MultipleObjectsReturned` exception
  235. will be raised if more than one object is found.
  236. ``get_list_or_404``
  237. ===================
  238. .. function:: get_list_or_404(klass, *args, **kwargs)
  239. Returns the result of :meth:`~django.db.models.query.QuerySet.filter()` on a
  240. given model manager cast to a list, raising :class:`~django.http.Http404` if
  241. the resulting list is empty.
  242. Required arguments
  243. ------------------
  244. ``klass``
  245. A :class:`~django.db.models.Model`, :class:`~django.db.models.Manager` or
  246. :class:`~django.db.models.query.QuerySet` instance from which to get the
  247. list.
  248. ``**kwargs``
  249. Lookup parameters, which should be in the format accepted by ``get()`` and
  250. ``filter()``.
  251. Example
  252. -------
  253. The following example gets all published objects from ``MyModel``::
  254. from django.shortcuts import get_list_or_404
  255. def my_view(request):
  256. my_objects = get_list_or_404(MyModel, published=True)
  257. This example is equivalent to::
  258. from django.http import Http404
  259. def my_view(request):
  260. my_objects = list(MyModel.objects.filter(published=True))
  261. if not my_objects:
  262. raise Http404