shortcuts.txt 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. =========================
  2. Django shortcut functions
  3. =========================
  4. .. module:: django.shortcuts
  5. :synopsis:
  6. Convience shortcuts that spam 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[, dictionary][, context_instance][, content_type][, status])
  14. .. versionadded:: 1.3
  15. Combines a given template with a given context dictionary and returns an
  16. :class:`~django.http.HttpResponse` object with that rendered text.
  17. :func:`render()` is the same as a call to
  18. :func:`render_to_response()` with a context_instance argument that
  19. that forces the use of a :class:`RequestContext`.
  20. Required arguments
  21. ------------------
  22. ``request``
  23. The request object used to generate this response.
  24. ``template``
  25. The full name of a template to use or sequence of template names.
  26. Optional arguments
  27. ------------------
  28. ``dictionary``
  29. A dictionary of values to add to the template context. By default, this
  30. is an empty dictionary. If a value in the dictionary is callable, the
  31. view will call it just before rendering the template.
  32. ``context_instance``
  33. The context instance to render the template with. By default, the template
  34. will be rendered with a ``RequestContext`` instance (filled with values from
  35. ``request`` and ```dictionary``).
  36. ``content_type``
  37. The MIME type to use for the resulting document. Defaults to the value of
  38. the :setting:`DEFAULT_CONTENT_TYPE` setting.
  39. ``status``
  40. The status code for the response. Defaults to ``200``.
  41. Example
  42. -------
  43. The following example renders the template ``myapp/index.html`` with the
  44. MIME type ``application/xhtml+xml``::
  45. from django.shortcuts import render
  46. def my_view(request):
  47. # View code here...
  48. return render(request, 'myapp/index.html', {"foo": "bar"},
  49. content_type="application/xhtml+xml")
  50. This example is equivalent to::
  51. from django.http import HttpResponse
  52. from django.template import Context, loader
  53. def my_view(request):
  54. # View code here...
  55. t = loader.get_template('myapp/template.html')
  56. c = RequestContext(request, {'foo': 'bar'})
  57. return HttpResponse(t.render(c),
  58. content_type="application/xhtml+xml")
  59. ``render_to_response``
  60. ======================
  61. .. function:: render_to_response(template[, dictionary][, context_instance][, mimetype])
  62. Renders a given template with a given context dictionary and returns an
  63. :class:`~django.http.HttpResponse` object with that rendered text.
  64. Required arguments
  65. ------------------
  66. ``template``
  67. The full name of a template to use or sequence of template names. If a
  68. sequence is given, the first template that exists will be used. See the
  69. :ref:`template loader documentation <ref-templates-api-the-python-api>`
  70. for more information on how templates are found.
  71. Optional arguments
  72. ------------------
  73. ``dictionary``
  74. A dictionary of values to add to the template context. By default, this
  75. is an empty dictionary. If a value in the dictionary is callable, the
  76. view will call it just before rendering the template.
  77. ``context_instance``
  78. The context instance to render the template with. By default, the template
  79. will be rendered with a :class:`~django.template.Context` instance (filled
  80. with values from ``dictionary``). If you need to use :ref:`context
  81. processors <subclassing-context-requestcontext>`, render the template with
  82. a :class:`~django.template.RequestContext` instance instead. Your code
  83. might look something like this::
  84. return render_to_response('my_template.html',
  85. my_data_dictionary,
  86. context_instance=RequestContext(request))
  87. ``mimetype``
  88. The MIME type to use for the resulting document. Defaults to the value of
  89. the :setting:`DEFAULT_CONTENT_TYPE` setting.
  90. Example
  91. -------
  92. The following example renders the template ``myapp/index.html`` with the
  93. MIME type ``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. mimetype="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/template.html')
  105. c = Context({'foo': 'bar'})
  106. return HttpResponse(t.render(c),
  107. mimetype="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 `get_absolute_url()` function will be called.
  115. * A view name, possibly with arguments: `urlresolvers.reverse()` will
  116. be used to reverse-resolve the name.
  117. * A URL, which will be used as-is for the redirect location.
  118. By default issues a temporary redirect; pass ``permanent=True`` to issue a
  119. permanent redirect
  120. Examples
  121. --------
  122. You can use the :func:`redirect` function in a number of ways.
  123. 1. By passing some object; that object's
  124. :meth:`~django.db.models.Model.get_absolute_url` method will be called
  125. to figure out the redirect URL::
  126. def my_view(request):
  127. ...
  128. object = MyModel.objects.get(...)
  129. return redirect(object)
  130. 2. By passing the name of a view and optionally some positional or
  131. keyword arguments; the URL will be reverse resolved using the
  132. :func:`~django.core.urlresolvers.reverse` method::
  133. def my_view(request):
  134. ...
  135. return redirect('some-view-name', foo='bar')
  136. 3. By passing a hardcoded URL to redirect to::
  137. def my_view(request):
  138. ...
  139. return redirect('/some/url/')
  140. This also works with full URLs::
  141. def my_view(request):
  142. ...
  143. return redirect('http://example.com/')
  144. By default, :func:`redirect` returns a temporary redirect. All of the above
  145. forms accept a ``permanent`` argument; if set to ``True`` a permanent redirect
  146. will be returned::
  147. def my_view(request):
  148. ...
  149. object = MyModel.objects.get(...)
  150. return redirect(object, permanent=True)
  151. ``get_object_or_404``
  152. =====================
  153. .. function:: get_object_or_404(klass, *args, **kwargs)
  154. Calls :meth:`~django.db.models.QuerySet.get()` on a given model manager,
  155. but it raises :class:`~django.http.Http404` instead of the model's
  156. :class:`~django.core.exceptions.DoesNotExist` exception.
  157. Required arguments
  158. ------------------
  159. ``klass``
  160. A :class:`~django.db.models.Model`, :class:`~django.db.models.Manager` or
  161. :class:`~django.db.models.QuerySet` instance from which to get the object.
  162. ``**kwargs``
  163. Lookup parameters, which should be in the format accepted by ``get()`` and
  164. ``filter()``.
  165. Example
  166. -------
  167. The following example gets the object with the primary key of 1 from
  168. ``MyModel``::
  169. from django.shortcuts import get_object_or_404
  170. def my_view(request):
  171. my_object = get_object_or_404(MyModel, pk=1)
  172. This example is equivalent to::
  173. from django.http import Http404
  174. def my_view(request):
  175. try:
  176. my_object = MyModel.objects.get(pk=1)
  177. except MyModel.DoesNotExist:
  178. raise Http404
  179. Note: As with ``get()``, a
  180. :class:`~django.core.exceptions.MultipleObjectsReturned` exception
  181. will be raised if more than one object is found.
  182. ``get_list_or_404``
  183. ===================
  184. .. function:: get_list_or_404(klass, *args, **kwargs)
  185. Returns the result of :meth:`~django.db.models.QuerySet.filter()` on a
  186. given model manager, raising :class:`~django.http.Http404` if the resulting
  187. list is empty.
  188. Required arguments
  189. ------------------
  190. ``klass``
  191. A :class:`~django.db.models.Model`, :class:`~django.db.models.Manager` or
  192. :class:`~django.db.models.query.QuerySet` instance from which to get the
  193. list.
  194. ``**kwargs``
  195. Lookup parameters, which should be in the format accepted by ``get()`` and
  196. ``filter()``.
  197. Example
  198. -------
  199. The following example gets all published objects from ``MyModel``::
  200. from django.shortcuts import get_list_or_404
  201. def my_view(request):
  202. my_objects = get_list_or_404(MyModel, published=True)
  203. This example is equivalent to::
  204. from django.http import Http404
  205. def my_view(request):
  206. my_objects = list(MyModel.objects.filter(published=True))
  207. if not my_objects:
  208. raise Http404