2008-08-24 06:25:40 +08:00
|
|
|
=============
|
2011-01-03 21:29:17 +08:00
|
|
|
Writing views
|
2008-08-24 06:25:40 +08:00
|
|
|
=============
|
|
|
|
|
|
|
|
A view function, or *view* for short, is simply a Python function that takes a
|
|
|
|
Web request and returns a Web response. This response can be the HTML contents
|
|
|
|
of a Web page, or a redirect, or a 404 error, or an XML document, or an image .
|
|
|
|
. . or anything, really. The view itself contains whatever arbitrary logic is
|
|
|
|
necessary to return that response. This code can live anywhere you want, as long
|
|
|
|
as it's on your Python path. There's no other requirement--no "magic," so to
|
2011-05-19 04:10:41 +08:00
|
|
|
speak. For the sake of putting the code *somewhere*, the convention is to
|
|
|
|
put views in a file called ``views.py``, placed in your project or
|
|
|
|
application directory.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
A simple view
|
|
|
|
=============
|
|
|
|
|
2014-08-18 22:30:44 +08:00
|
|
|
Here's a view that returns the current date and time, as an HTML document::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
from django.http import HttpResponse
|
|
|
|
import datetime
|
|
|
|
|
|
|
|
def current_datetime(request):
|
|
|
|
now = datetime.datetime.now()
|
|
|
|
html = "<html><body>It is now %s.</body></html>" % now
|
|
|
|
return HttpResponse(html)
|
|
|
|
|
|
|
|
Let's step through this code one line at a time:
|
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
* First, we import the class :class:`~django.http.HttpResponse` from the
|
|
|
|
:mod:`django.http` module, along with Python's ``datetime`` library.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
* Next, we define a function called ``current_datetime``. This is the view
|
|
|
|
function. Each view function takes an :class:`~django.http.HttpRequest`
|
|
|
|
object as its first parameter, which is typically named ``request``.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
Note that the name of the view function doesn't matter; it doesn't have to
|
|
|
|
be named in a certain way in order for Django to recognize it. We're
|
|
|
|
calling it ``current_datetime`` here, because that name clearly indicates
|
|
|
|
what it does.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
* The view returns an :class:`~django.http.HttpResponse` object that
|
|
|
|
contains the generated response. Each view function is responsible for
|
|
|
|
returning an :class:`~django.http.HttpResponse` object. (There are
|
|
|
|
exceptions, but we'll get to those later.)
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
.. admonition:: Django's Time Zone
|
2011-05-19 04:10:41 +08:00
|
|
|
|
2011-05-30 01:41:04 +08:00
|
|
|
Django includes a :setting:`TIME_ZONE` setting that defaults to
|
2008-08-24 06:25:40 +08:00
|
|
|
``America/Chicago``. This probably isn't where you live, so you might want
|
|
|
|
to change it in your settings file.
|
|
|
|
|
2011-01-03 21:29:17 +08:00
|
|
|
Mapping URLs to views
|
2008-08-24 06:25:40 +08:00
|
|
|
=====================
|
|
|
|
|
|
|
|
So, to recap, this view function returns an HTML page that includes the current
|
|
|
|
date and time. To display this view at a particular URL, you'll need to create a
|
2010-08-20 03:27:44 +08:00
|
|
|
*URLconf*; see :doc:`/topics/http/urls` for instructions.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Returning errors
|
|
|
|
================
|
|
|
|
|
2008-10-24 17:24:42 +08:00
|
|
|
Returning HTTP error codes in Django is easy. There are subclasses of
|
|
|
|
:class:`~django.http.HttpResponse` for a number of common HTTP status codes
|
|
|
|
other than 200 (which means *"OK"*). You can find the full list of available
|
|
|
|
subclasses in the :ref:`request/response <ref-httpresponse-subclasses>`
|
|
|
|
documentation. Just return an instance of one of those subclasses instead of
|
|
|
|
a normal :class:`~django.http.HttpResponse` in order to signify an error. For
|
|
|
|
example::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2013-05-18 20:00:52 +08:00
|
|
|
from django.http import HttpResponse, HttpResponseNotFound
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
def my_view(request):
|
|
|
|
# ...
|
|
|
|
if foo:
|
|
|
|
return HttpResponseNotFound('<h1>Page not found</h1>')
|
|
|
|
else:
|
|
|
|
return HttpResponse('<h1>Page was found</h1>')
|
|
|
|
|
2008-10-24 17:24:42 +08:00
|
|
|
There isn't a specialized subclass for every possible HTTP response code,
|
|
|
|
since many of them aren't going to be that common. However, as documented in
|
|
|
|
the :class:`~django.http.HttpResponse` documentation, you can also pass the
|
|
|
|
HTTP status code into the constructor for :class:`~django.http.HttpResponse`
|
|
|
|
to create a return class for any status code you like. For example::
|
|
|
|
|
2013-05-18 20:00:52 +08:00
|
|
|
from django.http import HttpResponse
|
|
|
|
|
2008-10-24 17:24:42 +08:00
|
|
|
def my_view(request):
|
|
|
|
# ...
|
|
|
|
|
|
|
|
# Return a "created" (201) response code.
|
|
|
|
return HttpResponse(status=201)
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Because 404 errors are by far the most common HTTP error, there's an easier way
|
|
|
|
to handle those errors.
|
|
|
|
|
2016-01-25 05:26:11 +08:00
|
|
|
The ``Http404`` exception
|
|
|
|
-------------------------
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2010-11-18 04:03:15 +08:00
|
|
|
.. class:: django.http.Http404()
|
|
|
|
|
2010-11-27 00:53:38 +08:00
|
|
|
When you return an error such as :class:`~django.http.HttpResponseNotFound`,
|
|
|
|
you're responsible for defining the HTML of the resulting error page::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
return HttpResponseNotFound('<h1>Page not found</h1>')
|
|
|
|
|
|
|
|
For convenience, and because it's a good idea to have a consistent 404 error page
|
|
|
|
across your site, Django provides an ``Http404`` exception. If you raise
|
|
|
|
``Http404`` at any point in a view function, Django will catch it and return the
|
|
|
|
standard error page for your application, along with an HTTP error code 404.
|
|
|
|
|
|
|
|
Example usage::
|
|
|
|
|
|
|
|
from django.http import Http404
|
2015-12-22 23:21:24 +08:00
|
|
|
from django.shortcuts import render
|
2013-05-18 20:00:52 +08:00
|
|
|
from polls.models import Poll
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
def detail(request, poll_id):
|
|
|
|
try:
|
|
|
|
p = Poll.objects.get(pk=poll_id)
|
|
|
|
except Poll.DoesNotExist:
|
2015-01-13 16:02:17 +08:00
|
|
|
raise Http404("Poll does not exist")
|
2015-12-22 23:21:24 +08:00
|
|
|
return render(request, 'polls/detail.html', {'poll': p})
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2015-08-28 15:55:17 +08:00
|
|
|
In order to show customized HTML when Django returns a 404, you can create an
|
|
|
|
HTML template named ``404.html`` and place it in the top level of your
|
|
|
|
template tree. This template will then be served when :setting:`DEBUG` is set
|
|
|
|
to ``False``.
|
|
|
|
|
|
|
|
When :setting:`DEBUG` is ``True``, you can provide a message to ``Http404`` and
|
|
|
|
it will appear in the standard 404 debug template. Use these messages for
|
|
|
|
debugging purposes; they generally aren't suitable for use in a production 404
|
|
|
|
template.
|
2015-01-13 16:02:17 +08:00
|
|
|
|
2011-09-11 12:01:41 +08:00
|
|
|
.. _customizing-error-views:
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Customizing error views
|
|
|
|
=======================
|
|
|
|
|
2014-05-25 04:39:55 +08:00
|
|
|
The default error views in Django should suffice for most Web applications,
|
|
|
|
but can easily be overridden if you need any custom behavior. Simply specify
|
|
|
|
the handlers as seen below in your URLconf (setting them anywhere else will
|
|
|
|
have no effect).
|
2012-08-20 21:01:57 +08:00
|
|
|
|
2014-05-25 04:39:55 +08:00
|
|
|
The :func:`~django.views.defaults.page_not_found` view is overridden by
|
|
|
|
:data:`~django.conf.urls.handler404`::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2014-05-25 04:39:55 +08:00
|
|
|
handler404 = 'mysite.views.my_custom_page_not_found_view'
|
2013-01-01 21:12:42 +08:00
|
|
|
|
2014-05-25 04:39:55 +08:00
|
|
|
The :func:`~django.views.defaults.server_error` view is overridden by
|
|
|
|
:data:`~django.conf.urls.handler500`::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
handler500 = 'mysite.views.my_custom_error_view'
|
|
|
|
|
2014-05-25 04:39:55 +08:00
|
|
|
The :func:`~django.views.defaults.permission_denied` view is overridden by
|
|
|
|
:data:`~django.conf.urls.handler403`::
|
2011-08-12 22:15:31 +08:00
|
|
|
|
|
|
|
handler403 = 'mysite.views.my_custom_permission_denied_view'
|
2013-05-16 07:14:28 +08:00
|
|
|
|
2014-05-25 04:39:55 +08:00
|
|
|
The :func:`~django.views.defaults.bad_request` view is overridden by
|
|
|
|
:data:`~django.conf.urls.handler400`::
|
2013-05-16 07:14:28 +08:00
|
|
|
|
|
|
|
handler400 = 'mysite.views.my_custom_bad_request_view'
|
2016-10-14 18:17:23 +08:00
|
|
|
|
|
|
|
.. seealso::
|
|
|
|
|
|
|
|
Use the :setting:`CSRF_FAILURE_VIEW` setting to override the CSRF error
|
|
|
|
view.
|
2018-09-19 18:57:34 +08:00
|
|
|
|
|
|
|
Testing custom error views
|
|
|
|
--------------------------
|
|
|
|
|
|
|
|
To test the response of a custom error handler, raise the appropriate exception
|
|
|
|
in a test view. For example::
|
|
|
|
|
|
|
|
from django.core.exceptions import PermissionDenied
|
|
|
|
from django.http import HttpResponse
|
|
|
|
from django.test import SimpleTestCase, override_settings
|
|
|
|
from django.urls import path
|
|
|
|
|
|
|
|
|
|
|
|
def response_error_handler(request, exception=None):
|
|
|
|
return HttpResponse('Error handler content', status=403)
|
|
|
|
|
|
|
|
|
|
|
|
def permission_denied_view(request):
|
|
|
|
raise PermissionDenied
|
|
|
|
|
|
|
|
|
|
|
|
urlpatterns = [
|
|
|
|
path('403/', permission_denied_view),
|
|
|
|
]
|
|
|
|
|
|
|
|
handler403 = response_error_handler
|
|
|
|
|
|
|
|
|
|
|
|
# ROOT_URLCONF must specify the module that contains handler403 = ...
|
|
|
|
@override_settings(ROOT_URLCONF=__name__)
|
|
|
|
class CustomErrorHandlerTests(SimpleTestCase):
|
|
|
|
|
|
|
|
def test_handler_renders_template_response(self):
|
|
|
|
response = self.client.get('/403/')
|
|
|
|
# Make assertions on the response here. For example:
|
|
|
|
self.assertContains(response, 'Error handler content', status_code=403)
|