| 1 |
============= |
| 2 |
Writing views |
| 3 |
============= |
| 4 |
|
| 5 |
A view function, or *view* for short, is a Python function that takes a |
| 6 |
web request and returns a web response. This response can be the HTML contents |
| 7 |
of a web page, or a redirect, or a 404 error, or an XML document, or an image . |
| 8 |
. . or anything, really. The view itself contains whatever arbitrary logic is |
| 9 |
necessary to return that response. This code can live anywhere you want, as long |
| 10 |
as it's on your Python path. There's no other requirement--no "magic," so to |
| 11 |
speak. For the sake of putting the code *somewhere*, the convention is to |
| 12 |
put views in a file called ``views.py``, placed in your project or |
| 13 |
application directory. |
| 14 |
|
| 15 |
A simple view |
| 16 |
============= |
| 17 |
|
| 18 |
Here's a view that returns the current date and time, as an HTML document:: |
| 19 |
|
| 20 |
from django.http import HttpResponse |
| 21 |
import datetime |
| 22 |
|
| 23 |
|
| 24 |
def current_datetime(request): |
| 25 |
now = datetime.datetime.now() |
| 26 |
html = '<html lang="en"><body>It is now %s.</body></html>' % now |
| 27 |
return HttpResponse(html) |
| 28 |
|
| 29 |
Let's step through this code one line at a time: |
| 30 |
|
| 31 |
* First, we import the class :class:`~django.http.HttpResponse` from the |
| 32 |
:mod:`django.http` module, along with Python's ``datetime`` library. |
| 33 |
|
| 34 |
* Next, we define a function called ``current_datetime``. This is the view |
| 35 |
function. Each view function takes an :class:`~django.http.HttpRequest` |
| 36 |
object as its first parameter, which is typically named ``request``. |
| 37 |
|
| 38 |
Note that the name of the view function doesn't matter; it doesn't have to |
| 39 |
be named in a certain way in order for Django to recognize it. We're |
| 40 |
calling it ``current_datetime`` here, because that name clearly indicates |
| 41 |
what it does. |
| 42 |
|
| 43 |
* The view returns an :class:`~django.http.HttpResponse` object that |
| 44 |
contains the generated response. Each view function is responsible for |
| 45 |
returning an :class:`~django.http.HttpResponse` object. (There are |
| 46 |
exceptions, but we'll get to those later.) |
| 47 |
|
| 48 |
.. admonition:: Django's Time Zone |
| 49 |
|
| 50 |
Django includes a :setting:`TIME_ZONE` setting that defaults to |
| 51 |
``America/Chicago``. This probably isn't where you live, so you might want |
| 52 |
to change it in your settings file. |
| 53 |
|
| 54 |
Mapping URLs to views |
| 55 |
===================== |
| 56 |
|
| 57 |
So, to recap, this view function returns an HTML page that includes the current |
| 58 |
date and time. To display this view at a particular URL, you'll need to create a |
| 59 |
*URLconf*; see :doc:`/topics/http/urls` for instructions. |
| 60 |
|
| 61 |
Returning errors |
| 62 |
================ |
| 63 |
|
| 64 |
Django provides help for returning HTTP error codes. There are subclasses of |
| 65 |
:class:`~django.http.HttpResponse` for a number of common HTTP status codes |
| 66 |
other than 200 (which means *"OK"*). You can find the full list of available |
| 67 |
subclasses in the :ref:`request/response <ref-httpresponse-subclasses>` |
| 68 |
documentation. Return an instance of one of those subclasses instead of a |
| 69 |
normal :class:`~django.http.HttpResponse` in order to signify an error. For |
| 70 |
example:: |
| 71 |
|
| 72 |
from django.http import HttpResponse, HttpResponseNotFound |
| 73 |
|
| 74 |
|
| 75 |
def my_view(request): |
| 76 |
# ... |
| 77 |
if foo: |
| 78 |
return HttpResponseNotFound("<h1>Page not found</h1>") |
| 79 |
else: |
| 80 |
return HttpResponse("<h1>Page was found</h1>") |
| 81 |
|
| 82 |
There isn't a specialized subclass for every possible HTTP response code, |
| 83 |
since many of them aren't going to be that common. However, as documented in |
| 84 |
the :class:`~django.http.HttpResponse` documentation, you can also pass the |
| 85 |
HTTP status code into the constructor for :class:`~django.http.HttpResponse` |
| 86 |
to create a return class for any status code you like. For example:: |
| 87 |
|
| 88 |
from django.http import HttpResponse |
| 89 |
|
| 90 |
|
| 91 |
def my_view(request): |
| 92 |
# ... |
| 93 |
|
| 94 |
# Return a "created" (201) response code. |
| 95 |
return HttpResponse(status=201) |
| 96 |
|
| 97 |
Because 404 errors are by far the most common HTTP error, there's an easier way |
| 98 |
to handle those errors. |
| 99 |
|
| 100 |
The ``Http404`` exception |
| 101 |
------------------------- |
| 102 |
|
| 103 |
.. class:: django.http.Http404() |
| 104 |
|
| 105 |
When you return an error such as :class:`~django.http.HttpResponseNotFound`, |
| 106 |
you're responsible for defining the HTML of the resulting error page:: |
| 107 |
|
| 108 |
return HttpResponseNotFound("<h1>Page not found</h1>") |
| 109 |
|
| 110 |
For convenience, and because it's a good idea to have a consistent 404 error page |
| 111 |
across your site, Django provides an ``Http404`` exception. If you raise |
| 112 |
``Http404`` at any point in a view function, Django will catch it and return the |
| 113 |
standard error page for your application, along with an HTTP error code 404. |
| 114 |
|
| 115 |
Example usage:: |
| 116 |
|
| 117 |
from django.http import Http404 |
| 118 |
from django.shortcuts import render |
| 119 |
from polls.models import Poll |
| 120 |
|
| 121 |
|
| 122 |
def detail(request, poll_id): |
| 123 |
try: |
| 124 |
p = Poll.objects.get(pk=poll_id) |
| 125 |
except Poll.DoesNotExist: |
| 126 |
raise Http404("Poll does not exist") |
| 127 |
return render(request, "polls/detail.html", {"poll": p}) |
| 128 |
|
| 129 |
In order to show customized HTML when Django returns a 404, you can create an |
| 130 |
HTML template named ``404.html`` and place it in the top level of your |
| 131 |
template tree. This template will then be served when :setting:`DEBUG` is set |
| 132 |
to ``False``. |
| 133 |
|
| 134 |
When :setting:`DEBUG` is ``True``, you can provide a message to ``Http404`` and |
| 135 |
it will appear in the standard 404 debug template. Use these messages for |
| 136 |
debugging purposes; they generally aren't suitable for use in a production 404 |
| 137 |
template. |
| 138 |
|
| 139 |
.. _customizing-error-views: |
| 140 |
|
| 141 |
Customizing error views |
| 142 |
======================= |
| 143 |
|
| 144 |
The default error views in Django should suffice for most web applications, |
| 145 |
but can easily be overridden if you need any custom behavior. Specify the |
| 146 |
handlers as seen below in your URLconf (setting them anywhere else will have no |
| 147 |
effect). |
| 148 |
|
| 149 |
The :func:`~django.views.defaults.page_not_found` view is overridden by |
| 150 |
:data:`~django.conf.urls.handler404`:: |
| 151 |
|
| 152 |
handler404 = "mysite.views.my_custom_page_not_found_view" |
| 153 |
|
| 154 |
The :func:`~django.views.defaults.server_error` view is overridden by |
| 155 |
:data:`~django.conf.urls.handler500`:: |
| 156 |
|
| 157 |
handler500 = "mysite.views.my_custom_error_view" |
| 158 |
|
| 159 |
The :func:`~django.views.defaults.permission_denied` view is overridden by |
| 160 |
:data:`~django.conf.urls.handler403`:: |
| 161 |
|
| 162 |
handler403 = "mysite.views.my_custom_permission_denied_view" |
| 163 |
|
| 164 |
The :func:`~django.views.defaults.bad_request` view is overridden by |
| 165 |
:data:`~django.conf.urls.handler400`:: |
| 166 |
|
| 167 |
handler400 = "mysite.views.my_custom_bad_request_view" |
| 168 |
|
| 169 |
.. seealso:: |
| 170 |
|
| 171 |
Use the :setting:`CSRF_FAILURE_VIEW` setting to override the CSRF error |
| 172 |
view. |
| 173 |
|
| 174 |
Testing custom error views |
| 175 |
-------------------------- |
| 176 |
|
| 177 |
To test the response of a custom error handler, raise the appropriate exception |
| 178 |
in a test view. For example:: |
| 179 |
|
| 180 |
from django.core.exceptions import PermissionDenied |
| 181 |
from django.http import HttpResponse |
| 182 |
from django.test import SimpleTestCase, override_settings |
| 183 |
from django.urls import path |
| 184 |
|
| 185 |
|
| 186 |
def response_error_handler(request, exception=None): |
| 187 |
return HttpResponse("Error handler content", status=403) |
| 188 |
|
| 189 |
|
| 190 |
def permission_denied_view(request): |
| 191 |
raise PermissionDenied |
| 192 |
|
| 193 |
|
| 194 |
urlpatterns = [ |
| 195 |
path("403/", permission_denied_view), |
| 196 |
] |
| 197 |
|
| 198 |
handler403 = response_error_handler |
| 199 |
|
| 200 |
|
| 201 |
# ROOT_URLCONF must specify the module that contains handler403 = ... |
| 202 |
@override_settings(ROOT_URLCONF=__name__) |
| 203 |
class CustomErrorHandlerTests(SimpleTestCase): |
| 204 |
def test_handler_renders_template_response(self): |
| 205 |
response = self.client.get("/403/") |
| 206 |
# Make assertions on the response here. For example: |
| 207 |
self.assertContains(response, "Error handler content", status_code=403) |
| 208 |
|
| 209 |
.. _async-views: |
| 210 |
|
| 211 |
Async views |
| 212 |
=========== |
| 213 |
|
| 214 |
As well as being synchronous functions, views can also be asynchronous |
| 215 |
("async") functions, normally defined using Python's ``async def`` syntax. |
| 216 |
Django will automatically detect these and run them in an async context. |
| 217 |
However, you will need to use an async server based on ASGI to get their |
| 218 |
performance benefits. |
| 219 |
|
| 220 |
Here's an example of an async view:: |
| 221 |
|
| 222 |
import datetime |
| 223 |
from django.http import HttpResponse |
| 224 |
|
| 225 |
|
| 226 |
async def current_datetime(request): |
| 227 |
now = datetime.datetime.now() |
| 228 |
html = '<html lang="en"><body>It is now %s.</body></html>' % now |
| 229 |
return HttpResponse(html) |
| 230 |
|
| 231 |
You can read more about Django's async support, and how to best use async |
| 232 |
views, in :doc:`/topics/async`. |