2
0

shortcuts.txt 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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=None, content_type=None, status=None, using=None)
  14. Combines a given template with a given context dictionary and returns an
  15. :class:`~django.http.HttpResponse` object with that rendered text.
  16. Django does not provide a shortcut function which returns a
  17. :class:`~django.template.response.TemplateResponse` because the constructor
  18. of :class:`~django.template.response.TemplateResponse` offers the same level
  19. of convenience as :func:`render()`.
  20. Required arguments
  21. ------------------
  22. ``request``
  23. The request object used to generate this response.
  24. ``template_name``
  25. The full name of a template to use or sequence of template names. If a
  26. sequence is given, the first template that exists will be used. See the
  27. :ref:`template loading documentation <template-loading>` for more
  28. information on how templates are found.
  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. ``content_type``
  36. The MIME type to use for the resulting document. Defaults to
  37. ``'text/html'``.
  38. ``status``
  39. The status code for the response. Defaults to ``200``.
  40. ``using``
  41. The :setting:`NAME <TEMPLATES-NAME>` of a template engine to use for
  42. loading the template.
  43. Example
  44. -------
  45. The following example renders the template ``myapp/index.html`` with the
  46. MIME type :mimetype:`application/xhtml+xml`::
  47. from django.shortcuts import render
  48. def my_view(request):
  49. # View code here...
  50. return render(
  51. request,
  52. "myapp/index.html",
  53. {
  54. "foo": "bar",
  55. },
  56. content_type="application/xhtml+xml",
  57. )
  58. This example is equivalent to::
  59. from django.http import HttpResponse
  60. from django.template import loader
  61. def my_view(request):
  62. # View code here...
  63. t = loader.get_template("myapp/index.html")
  64. c = {"foo": "bar"}
  65. return HttpResponse(t.render(c, request), content_type="application/xhtml+xml")
  66. ``redirect()``
  67. ==============
  68. .. function:: redirect(to, *args, permanent=False, preserve_request=False, **kwargs)
  69. Returns an :class:`~django.http.HttpResponseRedirect` to the appropriate URL
  70. for the arguments passed.
  71. The arguments could be:
  72. * A model: the model's :meth:`~django.db.models.Model.get_absolute_url()`
  73. function will be called.
  74. * A view name, possibly with arguments: :func:`~django.urls.reverse` will be
  75. used to reverse-resolve the name.
  76. * An absolute or relative URL, which will be used as-is for the redirect
  77. location.
  78. By default, a temporary redirect is issued with a 302 status code. If
  79. ``permanent=True``, a permanent redirect is issued with a 301 status code.
  80. If ``preserve_request=True``, the response instructs the user agent to
  81. preserve the method and body of the original request when issuing the
  82. redirect. In this case, temporary redirects use a 307 status code, and
  83. permanent redirects use a 308 status code. This is better illustrated in the
  84. following table:
  85. ========= ================ ================
  86. permanent preserve_request HTTP status code
  87. ========= ================ ================
  88. ``True`` ``False`` 301
  89. ``False`` ``False`` 302
  90. ``False`` ``True`` 307
  91. ``True`` ``True`` 308
  92. ========= ================ ================
  93. .. versionchanged:: 5.2
  94. The argument ``preserve_request`` was added.
  95. Examples
  96. --------
  97. You can use the :func:`redirect` function in a number of ways.
  98. #. By passing some object; that object's
  99. :meth:`~django.db.models.Model.get_absolute_url` method will be called
  100. to figure out the redirect URL::
  101. from django.shortcuts import redirect
  102. def my_view(request):
  103. ...
  104. obj = MyModel.objects.get(...)
  105. return redirect(obj)
  106. #. By passing the name of a view and optionally some positional or
  107. keyword arguments; the URL will be reverse resolved using the
  108. :func:`~django.urls.reverse` method::
  109. def my_view(request):
  110. ...
  111. return redirect("some-view-name", foo="bar")
  112. #. By passing a hardcoded URL to redirect to:
  113. ::
  114. def my_view(request):
  115. ...
  116. return redirect("/some/url/")
  117. This also works with full URLs:
  118. ::
  119. def my_view(request):
  120. ...
  121. return redirect("https://example.com/")
  122. By default, :func:`redirect` returns a temporary redirect. All of the above
  123. forms accept a ``permanent`` argument; if set to ``True`` a permanent redirect
  124. will be returned::
  125. def my_view(request):
  126. ...
  127. obj = MyModel.objects.get(...)
  128. return redirect(obj, permanent=True)
  129. Additionally, the ``preserve_request`` argument can be used to preserve the
  130. original HTTP method::
  131. def my_view(request):
  132. # ...
  133. obj = MyModel.objects.get(...)
  134. if request.method in ("POST", "PUT"):
  135. # Redirection preserves the original request method.
  136. return redirect(obj, preserve_request=True)
  137. # ...
  138. ``get_object_or_404()``
  139. =======================
  140. .. function:: get_object_or_404(klass, *args, **kwargs)
  141. .. function:: aget_object_or_404(klass, *args, **kwargs)
  142. *Asynchronous version*: ``aget_object_or_404()``
  143. Calls :meth:`~django.db.models.query.QuerySet.get()` on a given model
  144. manager, but it raises :class:`~django.http.Http404` instead of the model's
  145. :class:`~django.db.models.Model.DoesNotExist` exception.
  146. Arguments
  147. ---------
  148. ``klass``
  149. A :class:`~django.db.models.Model` class,
  150. a :class:`~django.db.models.Manager`,
  151. or a :class:`~django.db.models.query.QuerySet` instance from which to get
  152. the object.
  153. ``*args``
  154. :class:`Q objects <django.db.models.Q>`.
  155. ``**kwargs``
  156. Lookup parameters, which should be in the format accepted by ``get()`` and
  157. ``filter()``.
  158. Example
  159. -------
  160. The following example gets the object with the primary key of 1 from
  161. ``MyModel``::
  162. from django.shortcuts import get_object_or_404
  163. def my_view(request):
  164. obj = get_object_or_404(MyModel, pk=1)
  165. This example is equivalent to::
  166. from django.http import Http404
  167. def my_view(request):
  168. try:
  169. obj = MyModel.objects.get(pk=1)
  170. except MyModel.DoesNotExist:
  171. raise Http404("No MyModel matches the given query.")
  172. The most common use case is to pass a :class:`~django.db.models.Model`, as
  173. shown above. However, you can also pass a
  174. :class:`~django.db.models.query.QuerySet` instance::
  175. queryset = Book.objects.filter(title__startswith="M")
  176. get_object_or_404(queryset, pk=1)
  177. The above example is a bit contrived since it's equivalent to doing::
  178. get_object_or_404(Book, title__startswith="M", pk=1)
  179. but it can be useful if you are passed the ``queryset`` variable from somewhere
  180. else.
  181. Finally, you can also use a :class:`~django.db.models.Manager`. This is useful
  182. for example if you have a
  183. :ref:`custom manager<custom-managers>`::
  184. get_object_or_404(Book.dahl_objects, title="Matilda")
  185. You can also use
  186. :class:`related managers<django.db.models.fields.related.RelatedManager>`::
  187. author = Author.objects.get(name="Roald Dahl")
  188. get_object_or_404(author.book_set, title="Matilda")
  189. Note: As with ``get()``, a
  190. :class:`~django.core.exceptions.MultipleObjectsReturned` exception
  191. will be raised if more than one object is found.
  192. ``get_list_or_404()``
  193. =====================
  194. .. function:: get_list_or_404(klass, *args, **kwargs)
  195. .. function:: aget_list_or_404(klass, *args, **kwargs)
  196. *Asynchronous version*: ``aget_list_or_404()``
  197. Returns the result of :meth:`~django.db.models.query.QuerySet.filter()` on
  198. a given model manager cast to a list, raising :class:`~django.http.Http404`
  199. if the resulting list is empty.
  200. Arguments
  201. ---------
  202. ``klass``
  203. A :class:`~django.db.models.Model`, :class:`~django.db.models.Manager` or
  204. :class:`~django.db.models.query.QuerySet` instance from which to get the
  205. list.
  206. ``*args``
  207. :class:`Q objects <django.db.models.Q>`.
  208. ``**kwargs``
  209. Lookup parameters, which should be in the format accepted by ``get()`` and
  210. ``filter()``.
  211. Example
  212. -------
  213. The following example gets all published objects from ``MyModel``::
  214. from django.shortcuts import get_list_or_404
  215. def my_view(request):
  216. my_objects = get_list_or_404(MyModel, published=True)
  217. This example is equivalent to::
  218. from django.http import Http404
  219. def my_view(request):
  220. my_objects = list(MyModel.objects.filter(published=True))
  221. if not my_objects:
  222. raise Http404("No MyModel matches the given query.")