shortcuts.txt 7.7 KB

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