| 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 |
|
| 68 |
def my_view(request): |
| 69 |
# View code here... |
| 70 |
return render( |
| 71 |
request, |
| 72 |
"myapp/index.html", |
| 73 |
{ |
| 74 |
"foo": "bar", |
| 75 |
}, |
| 76 |
content_type="application/xhtml+xml", |
| 77 |
) |
| 78 |
|
| 79 |
This example is equivalent to:: |
| 80 |
|
| 81 |
from django.http import HttpResponse |
| 82 |
from django.template import loader |
| 83 |
|
| 84 |
|
| 85 |
def my_view(request): |
| 86 |
# View code here... |
| 87 |
t = loader.get_template("myapp/index.html") |
| 88 |
c = {"foo": "bar"} |
| 89 |
return HttpResponse(t.render(c, request), content_type="application/xhtml+xml") |
| 90 |
|
| 91 |
``redirect()`` |
| 92 |
============== |
| 93 |
|
| 94 |
.. function:: redirect(to, *args, permanent=False, preserve_request=False, **kwargs) |
| 95 |
|
| 96 |
Returns an :class:`~django.http.HttpResponseRedirect` to the appropriate URL |
| 97 |
for the arguments passed. |
| 98 |
|
| 99 |
The arguments could be: |
| 100 |
|
| 101 |
* A model: the model's :meth:`~django.db.models.Model.get_absolute_url()` |
| 102 |
function will be called. |
| 103 |
|
| 104 |
* A view name, possibly with arguments: :func:`~django.urls.reverse` will be |
| 105 |
used to reverse-resolve the name. |
| 106 |
|
| 107 |
* An absolute or relative URL, which will be used as-is for the redirect |
| 108 |
location. |
| 109 |
|
| 110 |
By default, a temporary redirect is issued with a 302 status code. If |
| 111 |
``permanent=True``, a permanent redirect is issued with a 301 status code. |
| 112 |
|
| 113 |
If ``preserve_request=True``, the response instructs the user agent to |
| 114 |
preserve the method and body of the original request when issuing the |
| 115 |
redirect. In this case, temporary redirects use a 307 status code, and |
| 116 |
permanent redirects use a 308 status code. This is better illustrated in the |
| 117 |
following table: |
| 118 |
|
| 119 |
========= ================ ================ |
| 120 |
permanent preserve_request HTTP status code |
| 121 |
========= ================ ================ |
| 122 |
``True`` ``False`` 301 |
| 123 |
``False`` ``False`` 302 |
| 124 |
``False`` ``True`` 307 |
| 125 |
``True`` ``True`` 308 |
| 126 |
========= ================ ================ |
| 127 |
|
| 128 |
.. versionchanged:: 5.2 |
| 129 |
|
| 130 |
The argument ``preserve_request`` was added. |
| 131 |
|
| 132 |
Examples |
| 133 |
-------- |
| 134 |
|
| 135 |
You can use the :func:`redirect` function in a number of ways. |
| 136 |
|
| 137 |
#. By passing some object; that object's |
| 138 |
:meth:`~django.db.models.Model.get_absolute_url` method will be called |
| 139 |
to figure out the redirect URL:: |
| 140 |
|
| 141 |
from django.shortcuts import redirect |
| 142 |
|
| 143 |
|
| 144 |
def my_view(request): |
| 145 |
... |
| 146 |
obj = MyModel.objects.get(...) |
| 147 |
return redirect(obj) |
| 148 |
|
| 149 |
#. By passing the name of a view and optionally some positional or |
| 150 |
keyword arguments; the URL will be reverse resolved using the |
| 151 |
:func:`~django.urls.reverse` method:: |
| 152 |
|
| 153 |
def my_view(request): |
| 154 |
... |
| 155 |
return redirect("some-view-name", foo="bar") |
| 156 |
|
| 157 |
#. By passing a hardcoded URL to redirect to: |
| 158 |
:: |
| 159 |
|
| 160 |
def my_view(request): |
| 161 |
... |
| 162 |
return redirect("/some/url/") |
| 163 |
|
| 164 |
This also works with full URLs: |
| 165 |
:: |
| 166 |
|
| 167 |
def my_view(request): |
| 168 |
... |
| 169 |
return redirect("https://example.com/") |
| 170 |
|
| 171 |
By default, :func:`redirect` returns a temporary redirect. All of the above |
| 172 |
forms accept a ``permanent`` argument; if set to ``True`` a permanent redirect |
| 173 |
will be returned:: |
| 174 |
|
| 175 |
def my_view(request): |
| 176 |
... |
| 177 |
obj = MyModel.objects.get(...) |
| 178 |
return redirect(obj, permanent=True) |
| 179 |
|
| 180 |
Additionally, the ``preserve_request`` argument can be used to preserve the |
| 181 |
original HTTP method:: |
| 182 |
|
| 183 |
def my_view(request): |
| 184 |
# ... |
| 185 |
obj = MyModel.objects.get(...) |
| 186 |
if request.method in ("POST", "PUT"): |
| 187 |
# Redirection preserves the original request method. |
| 188 |
return redirect(obj, preserve_request=True) |
| 189 |
# ... |
| 190 |
|
| 191 |
``get_object_or_404()`` |
| 192 |
======================= |
| 193 |
|
| 194 |
.. function:: get_object_or_404(klass, *args, **kwargs) |
| 195 |
.. function:: aget_object_or_404(klass, *args, **kwargs) |
| 196 |
|
| 197 |
*Asynchronous version*: ``aget_object_or_404()`` |
| 198 |
|
| 199 |
Calls :meth:`~django.db.models.query.QuerySet.get()` on a given model |
| 200 |
manager, but it raises :class:`~django.http.Http404` instead of the model's |
| 201 |
:class:`~django.db.models.Model.DoesNotExist` exception. |
| 202 |
|
| 203 |
Arguments |
| 204 |
--------- |
| 205 |
|
| 206 |
``klass`` |
| 207 |
A :class:`~django.db.models.Model` class, |
| 208 |
a :class:`~django.db.models.Manager`, |
| 209 |
or a :class:`~django.db.models.query.QuerySet` instance from which to get |
| 210 |
the object. |
| 211 |
|
| 212 |
``*args`` |
| 213 |
:class:`Q objects <django.db.models.Q>`. |
| 214 |
|
| 215 |
``**kwargs`` |
| 216 |
Lookup parameters, which should be in the format accepted by ``get()`` and |
| 217 |
``filter()``. |
| 218 |
|
| 219 |
Example |
| 220 |
------- |
| 221 |
|
| 222 |
The following example gets the object with the primary key of 1 from |
| 223 |
``MyModel``:: |
| 224 |
|
| 225 |
from django.shortcuts import get_object_or_404 |
| 226 |
|
| 227 |
|
| 228 |
def my_view(request): |
| 229 |
obj = get_object_or_404(MyModel, pk=1) |
| 230 |
|
| 231 |
This example is equivalent to:: |
| 232 |
|
| 233 |
from django.http import Http404 |
| 234 |
|
| 235 |
|
| 236 |
def my_view(request): |
| 237 |
try: |
| 238 |
obj = MyModel.objects.get(pk=1) |
| 239 |
except MyModel.DoesNotExist: |
| 240 |
raise Http404("No MyModel matches the given query.") |
| 241 |
|
| 242 |
The most common use case is to pass a :class:`~django.db.models.Model`, as |
| 243 |
shown above. However, you can also pass a |
| 244 |
:class:`~django.db.models.query.QuerySet` instance:: |
| 245 |
|
| 246 |
queryset = Book.objects.filter(title__startswith="M") |
| 247 |
get_object_or_404(queryset, pk=1) |
| 248 |
|
| 249 |
The above example is a bit contrived since it's equivalent to doing:: |
| 250 |
|
| 251 |
get_object_or_404(Book, title__startswith="M", pk=1) |
| 252 |
|
| 253 |
but it can be useful if you are passed the ``queryset`` variable from somewhere |
| 254 |
else. |
| 255 |
|
| 256 |
Finally, you can also use a :class:`~django.db.models.Manager`. This is useful |
| 257 |
for example if you have a |
| 258 |
:ref:`custom manager<custom-managers>`:: |
| 259 |
|
| 260 |
get_object_or_404(Book.dahl_objects, title="Matilda") |
| 261 |
|
| 262 |
You can also use |
| 263 |
:class:`related managers<django.db.models.fields.related.RelatedManager>`:: |
| 264 |
|
| 265 |
author = Author.objects.get(name="Roald Dahl") |
| 266 |
get_object_or_404(author.book_set, title="Matilda") |
| 267 |
|
| 268 |
Note: As with ``get()``, a |
| 269 |
:class:`~django.core.exceptions.MultipleObjectsReturned` exception |
| 270 |
will be raised if more than one object is found. |
| 271 |
|
| 272 |
``get_list_or_404()`` |
| 273 |
===================== |
| 274 |
|
| 275 |
.. function:: get_list_or_404(klass, *args, **kwargs) |
| 276 |
.. function:: aget_list_or_404(klass, *args, **kwargs) |
| 277 |
|
| 278 |
*Asynchronous version*: ``aget_list_or_404()`` |
| 279 |
|
| 280 |
Returns the result of :meth:`~django.db.models.query.QuerySet.filter()` on |
| 281 |
a given model manager cast to a list, raising :class:`~django.http.Http404` |
| 282 |
if the resulting list is empty. |
| 283 |
|
| 284 |
Arguments |
| 285 |
--------- |
| 286 |
|
| 287 |
``klass`` |
| 288 |
A :class:`~django.db.models.Model`, :class:`~django.db.models.Manager` or |
| 289 |
:class:`~django.db.models.query.QuerySet` instance from which to get the |
| 290 |
list. |
| 291 |
|
| 292 |
``*args`` |
| 293 |
:class:`Q objects <django.db.models.Q>`. |
| 294 |
|
| 295 |
``**kwargs`` |
| 296 |
Lookup parameters, which should be in the format accepted by ``get()`` and |
| 297 |
``filter()``. |
| 298 |
|
| 299 |
Example |
| 300 |
------- |
| 301 |
|
| 302 |
The following example gets all published objects from ``MyModel``:: |
| 303 |
|
| 304 |
from django.shortcuts import get_list_or_404 |
| 305 |
|
| 306 |
|
| 307 |
def my_view(request): |
| 308 |
my_objects = get_list_or_404(MyModel, published=True) |
| 309 |
|
| 310 |
This example is equivalent to:: |
| 311 |
|
| 312 |
from django.http import Http404 |
| 313 |
|
| 314 |
|
| 315 |
def my_view(request): |
| 316 |
my_objects = list(MyModel.objects.filter(published=True)) |
| 317 |
if not my_objects: |
| 318 |
raise Http404("No MyModel matches the given query.") |
| 319 |
|