shortcuts.txt 12 KB

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