shortcuts.txt 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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[, dictionary][, context_instance][, content_type][, status][, current_app][, dirs])
  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. Required arguments
  20. ------------------
  21. ``request``
  22. The request object used to generate this response.
  23. ``template_name``
  24. The full name of a template to use or sequence of template names.
  25. Optional arguments
  26. ------------------
  27. ``dictionary``
  28. A dictionary of values to add to the template context. By default, this
  29. is an empty dictionary. If a value in the dictionary is callable, the
  30. view will call it just before rendering the template.
  31. ``context_instance``
  32. The context instance to render the template with. By default, the template
  33. will be rendered with a ``RequestContext`` instance (filled with values from
  34. ``request`` and ``dictionary``).
  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. ``current_app``
  41. A hint indicating which application contains the current view. See the
  42. :ref:`namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`
  43. for more information.
  44. ``dirs``
  45. A tuple or list of values to override the :setting:`TEMPLATE_DIRS` setting.
  46. .. versionchanged:: 1.7
  47. The ``dirs`` parameter was added.
  48. Example
  49. -------
  50. The following example renders the template ``myapp/index.html`` with the
  51. MIME type :mimetype:`application/xhtml+xml`::
  52. from django.shortcuts import render
  53. def my_view(request):
  54. # View code here...
  55. return render(request, 'myapp/index.html', {"foo": "bar"},
  56. content_type="application/xhtml+xml")
  57. This example is equivalent to::
  58. from django.http import HttpResponse
  59. from django.template import RequestContext, loader
  60. def my_view(request):
  61. # View code here...
  62. t = loader.get_template('myapp/template.html')
  63. c = RequestContext(request, {'foo': 'bar'})
  64. return HttpResponse(t.render(c),
  65. content_type="application/xhtml+xml")
  66. If you want to override the :setting:`TEMPLATE_DIRS` setting, use the
  67. ``dirs`` parameter::
  68. from django.shortcuts import render
  69. def my_view(request):
  70. # View code here...
  71. return render(request, 'index.html', dirs=('custom_templates',))
  72. ``render_to_response``
  73. ======================
  74. .. function:: render_to_response(template_name[, dictionary][, context_instance][, content_type][, dirs])
  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 loader documentation <ref-templates-api-the-python-api>`
  83. for more information on how templates are found.
  84. Optional arguments
  85. ------------------
  86. ``dictionary``
  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. ``context_instance``
  91. The context instance to render the template with. By default, the template
  92. will be rendered with a :class:`~django.template.Context` instance (filled
  93. with values from ``dictionary``). If you need to use :ref:`context
  94. processors <subclassing-context-requestcontext>`, render the template with
  95. a :class:`~django.template.RequestContext` instance instead. Your code
  96. might look something like this::
  97. return render_to_response('my_template.html',
  98. my_data_dictionary,
  99. context_instance=RequestContext(request))
  100. ``content_type``
  101. The MIME type to use for the resulting document. Defaults to the value of
  102. the :setting:`DEFAULT_CONTENT_TYPE` setting.
  103. ``dirs``
  104. A tuple or list of values to override the :setting:`TEMPLATE_DIRS` setting.
  105. .. versionchanged:: 1.7
  106. The ``dirs`` parameter was added.
  107. Example
  108. -------
  109. The following example renders the template ``myapp/index.html`` with the
  110. MIME type :mimetype:`application/xhtml+xml`::
  111. from django.shortcuts import render_to_response
  112. def my_view(request):
  113. # View code here...
  114. return render_to_response('myapp/index.html', {"foo": "bar"},
  115. mimetype="application/xhtml+xml")
  116. This example is equivalent to::
  117. from django.http import HttpResponse
  118. from django.template import Context, loader
  119. def my_view(request):
  120. # View code here...
  121. t = loader.get_template('myapp/template.html')
  122. c = Context({'foo': 'bar'})
  123. return HttpResponse(t.render(c),
  124. content_type="application/xhtml+xml")
  125. If you want to override the :setting:`TEMPLATE_DIRS` setting, use the
  126. ``dirs`` parameter::
  127. from django.shortcuts import render_to_response
  128. def my_view(request):
  129. # View code here...
  130. return render_to_response('index.html', dirs=('custom_templates',))
  131. ``redirect``
  132. ============
  133. .. function:: redirect(to[, permanent=False], *args, **kwargs)
  134. Returns an :class:`~django.http.HttpResponseRedirect` to the appropriate URL
  135. for the arguments passed.
  136. The arguments could be:
  137. * A model: the model's :meth:`~django.db.models.Model.get_absolute_url()`
  138. function will be called.
  139. * A view name, possibly with arguments: :func:`urlresolvers.reverse
  140. <django.core.urlresolvers.reverse>` will be used to reverse-resolve the
  141. name.
  142. * A URL, which will be used as-is for the redirect location.
  143. By default issues a temporary redirect; pass ``permanent=True`` to issue a
  144. permanent redirect
  145. Examples
  146. --------
  147. You can use the :func:`redirect` function in a number of ways.
  148. 1. By passing some object; that object's
  149. :meth:`~django.db.models.Model.get_absolute_url` method will be called
  150. to figure out the redirect URL::
  151. from django.shortcuts import redirect
  152. def my_view(request):
  153. ...
  154. object = MyModel.objects.get(...)
  155. return redirect(object)
  156. 2. By passing the name of a view and optionally some positional or
  157. keyword arguments; the URL will be reverse resolved using the
  158. :func:`~django.core.urlresolvers.reverse` method::
  159. def my_view(request):
  160. ...
  161. return redirect('some-view-name', foo='bar')
  162. 3. By passing a hardcoded URL to redirect to::
  163. def my_view(request):
  164. ...
  165. return redirect('/some/url/')
  166. This also works with full URLs::
  167. def my_view(request):
  168. ...
  169. return redirect('http://example.com/')
  170. By default, :func:`redirect` returns a temporary redirect. All of the above
  171. forms accept a ``permanent`` argument; if set to ``True`` a permanent redirect
  172. will be returned::
  173. def my_view(request):
  174. ...
  175. object = MyModel.objects.get(...)
  176. return redirect(object, permanent=True)
  177. ``get_object_or_404``
  178. =====================
  179. .. function:: get_object_or_404(klass, *args, **kwargs)
  180. Calls :meth:`~django.db.models.query.QuerySet.get()` on a given model manager,
  181. but it raises :class:`~django.http.Http404` instead of the model's
  182. :class:`~django.core.exceptions.DoesNotExist` exception.
  183. Required arguments
  184. ------------------
  185. ``klass``
  186. A :class:`~django.db.models.Model`, :class:`~django.db.models.Manager` or
  187. :class:`~django.db.models.query.QuerySet` instance from which to get the
  188. object.
  189. ``**kwargs``
  190. Lookup parameters, which should be in the format accepted by ``get()`` and
  191. ``filter()``.
  192. Example
  193. -------
  194. The following example gets the object with the primary key of 1 from
  195. ``MyModel``::
  196. from django.shortcuts import get_object_or_404
  197. def my_view(request):
  198. my_object = get_object_or_404(MyModel, pk=1)
  199. This example is equivalent to::
  200. from django.http import Http404
  201. def my_view(request):
  202. try:
  203. my_object = MyModel.objects.get(pk=1)
  204. except MyModel.DoesNotExist:
  205. raise Http404
  206. Note: As with ``get()``, a
  207. :class:`~django.core.exceptions.MultipleObjectsReturned` exception
  208. will be raised if more than one object is found.
  209. ``get_list_or_404``
  210. ===================
  211. .. function:: get_list_or_404(klass, *args, **kwargs)
  212. Returns the result of :meth:`~django.db.models.query.QuerySet.filter()` on a
  213. given model manager cast to a list, raising :class:`~django.http.Http404` if
  214. the resulting list is empty.
  215. Required arguments
  216. ------------------
  217. ``klass``
  218. A :class:`~django.db.models.Model`, :class:`~django.db.models.Manager` or
  219. :class:`~django.db.models.query.QuerySet` instance from which to get the
  220. list.
  221. ``**kwargs``
  222. Lookup parameters, which should be in the format accepted by ``get()`` and
  223. ``filter()``.
  224. Example
  225. -------
  226. The following example gets all published objects from ``MyModel``::
  227. from django.shortcuts import get_list_or_404
  228. def my_view(request):
  229. my_objects = get_list_or_404(MyModel, published=True)
  230. This example is equivalent to::
  231. from django.http import Http404
  232. def my_view(request):
  233. my_objects = list(MyModel.objects.filter(published=True))
  234. if not my_objects:
  235. raise Http404