shortcuts.txt 6.8 KB

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