shortcuts.txt 8.0 KB

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