shortcuts.txt 11 KB

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