shortcuts.txt 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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 the value of
  37. the :setting:`DEFAULT_CONTENT_TYPE` setting.
  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(request, 'myapp/index.html', {
  51. 'foo': 'bar',
  52. }, content_type='application/xhtml+xml')
  53. This example is equivalent to::
  54. from django.http import HttpResponse
  55. from django.template import loader
  56. def my_view(request):
  57. # View code here...
  58. t = loader.get_template('myapp/index.html')
  59. c = {'foo': 'bar'}
  60. return HttpResponse(t.render(c, request), content_type='application/xhtml+xml')
  61. ``redirect()``
  62. ==============
  63. .. function:: redirect(to, permanent=False, *args, **kwargs)
  64. Returns an :class:`~django.http.HttpResponseRedirect` to the appropriate URL
  65. for the arguments passed.
  66. The arguments could be:
  67. * A model: the model's :meth:`~django.db.models.Model.get_absolute_url()`
  68. function will be called.
  69. * A view name, possibly with arguments: :func:`~django.urls.reverse` will be
  70. used to reverse-resolve the name.
  71. * An absolute or relative URL, which will be used as-is for the redirect
  72. location.
  73. By default issues a temporary redirect; pass ``permanent=True`` to issue a
  74. permanent redirect.
  75. Examples
  76. --------
  77. You can use the :func:`redirect` function in a number of ways.
  78. #. By passing some object; that object's
  79. :meth:`~django.db.models.Model.get_absolute_url` method will be called
  80. to figure out the redirect URL::
  81. from django.shortcuts import redirect
  82. def my_view(request):
  83. ...
  84. obj = MyModel.objects.get(...)
  85. return redirect(obj)
  86. #. By passing the name of a view and optionally some positional or
  87. keyword arguments; the URL will be reverse resolved using the
  88. :func:`~django.urls.reverse` method::
  89. def my_view(request):
  90. ...
  91. return redirect('some-view-name', foo='bar')
  92. #. By passing a hardcoded URL to redirect to::
  93. def my_view(request):
  94. ...
  95. return redirect('/some/url/')
  96. This also works with full URLs::
  97. def my_view(request):
  98. ...
  99. return redirect('https://example.com/')
  100. By default, :func:`redirect` returns a temporary redirect. All of the above
  101. forms accept a ``permanent`` argument; if set to ``True`` a permanent redirect
  102. will be returned::
  103. def my_view(request):
  104. ...
  105. obj = MyModel.objects.get(...)
  106. return redirect(obj, permanent=True)
  107. ``get_object_or_404()``
  108. =======================
  109. .. function:: get_object_or_404(klass, *args, **kwargs)
  110. Calls :meth:`~django.db.models.query.QuerySet.get()` on a given model manager,
  111. but it raises :class:`~django.http.Http404` instead of the model's
  112. :class:`~django.db.models.Model.DoesNotExist` exception.
  113. Required arguments
  114. ------------------
  115. ``klass``
  116. A :class:`~django.db.models.Model` class,
  117. a :class:`~django.db.models.Manager`,
  118. or a :class:`~django.db.models.query.QuerySet` instance from which to get
  119. the object.
  120. ``**kwargs``
  121. Lookup parameters, which should be in the format accepted by ``get()`` and
  122. ``filter()``.
  123. Example
  124. -------
  125. The following example gets the object with the primary key of 1 from
  126. ``MyModel``::
  127. from django.shortcuts import get_object_or_404
  128. def my_view(request):
  129. obj = get_object_or_404(MyModel, pk=1)
  130. This example is equivalent to::
  131. from django.http import Http404
  132. def my_view(request):
  133. try:
  134. obj = MyModel.objects.get(pk=1)
  135. except MyModel.DoesNotExist:
  136. raise Http404("No MyModel matches the given query.")
  137. The most common use case is to pass a :class:`~django.db.models.Model`, as
  138. shown above. However, you can also pass a
  139. :class:`~django.db.models.query.QuerySet` instance::
  140. queryset = Book.objects.filter(title__startswith='M')
  141. get_object_or_404(queryset, pk=1)
  142. The above example is a bit contrived since it's equivalent to doing::
  143. get_object_or_404(Book, title__startswith='M', pk=1)
  144. but it can be useful if you are passed the ``queryset`` variable from somewhere
  145. else.
  146. Finally, you can also use a :class:`~django.db.models.Manager`. This is useful
  147. for example if you have a
  148. :ref:`custom manager<custom-managers>`::
  149. get_object_or_404(Book.dahl_objects, title='Matilda')
  150. You can also use
  151. :class:`related managers<django.db.models.fields.related.RelatedManager>`::
  152. author = Author.objects.get(name='Roald Dahl')
  153. get_object_or_404(author.book_set, title='Matilda')
  154. Note: As with ``get()``, a
  155. :class:`~django.core.exceptions.MultipleObjectsReturned` exception
  156. will be raised if more than one object is found.
  157. ``get_list_or_404()``
  158. =====================
  159. .. function:: get_list_or_404(klass, *args, **kwargs)
  160. Returns the result of :meth:`~django.db.models.query.QuerySet.filter()` on a
  161. given model manager cast to a list, raising :class:`~django.http.Http404` if
  162. the resulting list is empty.
  163. Required arguments
  164. ------------------
  165. ``klass``
  166. A :class:`~django.db.models.Model`, :class:`~django.db.models.Manager` or
  167. :class:`~django.db.models.query.QuerySet` instance from which to get the
  168. list.
  169. ``**kwargs``
  170. Lookup parameters, which should be in the format accepted by ``get()`` and
  171. ``filter()``.
  172. Example
  173. -------
  174. The following example gets all published objects from ``MyModel``::
  175. from django.shortcuts import get_list_or_404
  176. def my_view(request):
  177. my_objects = get_list_or_404(MyModel, published=True)
  178. This example is equivalent to::
  179. from django.http import Http404
  180. def my_view(request):
  181. my_objects = list(MyModel.objects.filter(published=True))
  182. if not my_objects:
  183. raise Http404("No MyModel matches the given query.")