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