shortcuts.txt 9.7 KB

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