2
0

shortcuts.txt 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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, **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 issues a temporary redirect; pass ``permanent=True`` to issue a
  79. permanent redirect.
  80. Examples
  81. --------
  82. You can use the :func:`redirect` function in a number of ways.
  83. #. By passing some object; that object's
  84. :meth:`~django.db.models.Model.get_absolute_url` method will be called
  85. to figure out the redirect URL::
  86. from django.shortcuts import redirect
  87. def my_view(request):
  88. ...
  89. obj = MyModel.objects.get(...)
  90. return redirect(obj)
  91. #. By passing the name of a view and optionally some positional or
  92. keyword arguments; the URL will be reverse resolved using the
  93. :func:`~django.urls.reverse` method::
  94. def my_view(request):
  95. ...
  96. return redirect("some-view-name", foo="bar")
  97. #. By passing a hardcoded URL to redirect to:
  98. ::
  99. def my_view(request):
  100. ...
  101. return redirect("/some/url/")
  102. This also works with full URLs:
  103. ::
  104. def my_view(request):
  105. ...
  106. return redirect("https://example.com/")
  107. By default, :func:`redirect` returns a temporary redirect. All of the above
  108. forms accept a ``permanent`` argument; if set to ``True`` a permanent redirect
  109. will be returned::
  110. def my_view(request):
  111. ...
  112. obj = MyModel.objects.get(...)
  113. return redirect(obj, permanent=True)
  114. ``get_object_or_404()``
  115. =======================
  116. .. function:: get_object_or_404(klass, *args, **kwargs)
  117. .. function:: aget_object_or_404(klass, *args, **kwargs)
  118. *Asynchronous version*: ``aget_object_or_404()``
  119. Calls :meth:`~django.db.models.query.QuerySet.get()` on a given model
  120. manager, but it raises :class:`~django.http.Http404` instead of the model's
  121. :class:`~django.db.models.Model.DoesNotExist` exception.
  122. Arguments
  123. ---------
  124. ``klass``
  125. A :class:`~django.db.models.Model` class,
  126. a :class:`~django.db.models.Manager`,
  127. or a :class:`~django.db.models.query.QuerySet` instance from which to get
  128. the object.
  129. ``*args``
  130. :class:`Q objects <django.db.models.Q>`.
  131. ``**kwargs``
  132. Lookup parameters, which should be in the format accepted by ``get()`` and
  133. ``filter()``.
  134. Example
  135. -------
  136. The following example gets the object with the primary key of 1 from
  137. ``MyModel``::
  138. from django.shortcuts import get_object_or_404
  139. def my_view(request):
  140. obj = get_object_or_404(MyModel, pk=1)
  141. This example is equivalent to::
  142. from django.http import Http404
  143. def my_view(request):
  144. try:
  145. obj = MyModel.objects.get(pk=1)
  146. except MyModel.DoesNotExist:
  147. raise Http404("No MyModel matches the given query.")
  148. The most common use case is to pass a :class:`~django.db.models.Model`, as
  149. shown above. However, you can also pass a
  150. :class:`~django.db.models.query.QuerySet` instance::
  151. queryset = Book.objects.filter(title__startswith="M")
  152. get_object_or_404(queryset, pk=1)
  153. The above example is a bit contrived since it's equivalent to doing::
  154. get_object_or_404(Book, title__startswith="M", pk=1)
  155. but it can be useful if you are passed the ``queryset`` variable from somewhere
  156. else.
  157. Finally, you can also use a :class:`~django.db.models.Manager`. This is useful
  158. for example if you have a
  159. :ref:`custom manager<custom-managers>`::
  160. get_object_or_404(Book.dahl_objects, title="Matilda")
  161. You can also use
  162. :class:`related managers<django.db.models.fields.related.RelatedManager>`::
  163. author = Author.objects.get(name="Roald Dahl")
  164. get_object_or_404(author.book_set, title="Matilda")
  165. Note: As with ``get()``, a
  166. :class:`~django.core.exceptions.MultipleObjectsReturned` exception
  167. will be raised if more than one object is found.
  168. .. versionchanged:: 5.0
  169. ``aget_object_or_404()`` function was added.
  170. ``get_list_or_404()``
  171. =====================
  172. .. function:: get_list_or_404(klass, *args, **kwargs)
  173. .. function:: aget_list_or_404(klass, *args, **kwargs)
  174. *Asynchronous version*: ``aget_list_or_404()``
  175. Returns the result of :meth:`~django.db.models.query.QuerySet.filter()` on
  176. a given model manager cast to a list, raising :class:`~django.http.Http404`
  177. if the resulting list is empty.
  178. Arguments
  179. ---------
  180. ``klass``
  181. A :class:`~django.db.models.Model`, :class:`~django.db.models.Manager` or
  182. :class:`~django.db.models.query.QuerySet` instance from which to get the
  183. list.
  184. ``*args``
  185. :class:`Q objects <django.db.models.Q>`.
  186. ``**kwargs``
  187. Lookup parameters, which should be in the format accepted by ``get()`` and
  188. ``filter()``.
  189. Example
  190. -------
  191. The following example gets all published objects from ``MyModel``::
  192. from django.shortcuts import get_list_or_404
  193. def my_view(request):
  194. my_objects = get_list_or_404(MyModel, published=True)
  195. This example is equivalent to::
  196. from django.http import Http404
  197. def my_view(request):
  198. my_objects = list(MyModel.objects.filter(published=True))
  199. if not my_objects:
  200. raise Http404("No MyModel matches the given query.")
  201. .. versionchanged:: 5.0
  202. ``aget_list_or_404()`` function was added.