2008-08-23 22:25:40 +00:00
|
|
|
=============
|
2011-01-03 13:29:17 +00:00
|
|
|
Writing views
|
2008-08-23 22:25:40 +00: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-18 20:10:41 +00: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-23 22:25:40 +00:00
|
|
|
|
|
|
|
A simple view
|
|
|
|
=============
|
|
|
|
|
|
|
|
Here's a view that returns the current date and time, as an HTML document:
|
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
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 00:12:01 +00:00
|
|
|
* First, we import the class :class:`~django.http.HttpResponse` from the
|
|
|
|
:mod:`django.http` module, along with Python's ``datetime`` library.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2011-10-14 00:12:01 +00: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-23 22:25:40 +00:00
|
|
|
|
2011-10-14 00:12:01 +00: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-23 22:25:40 +00:00
|
|
|
|
2011-10-14 00:12:01 +00: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-23 22:25:40 +00:00
|
|
|
|
|
|
|
.. admonition:: Django's Time Zone
|
2011-05-18 20:10:41 +00:00
|
|
|
|
2011-05-29 17:41:04 +00:00
|
|
|
Django includes a :setting:`TIME_ZONE` setting that defaults to
|
2008-08-23 22:25:40 +00:00
|
|
|
``America/Chicago``. This probably isn't where you live, so you might want
|
|
|
|
to change it in your settings file.
|
|
|
|
|
2011-01-03 13:29:17 +00:00
|
|
|
Mapping URLs to views
|
2008-08-23 22:25:40 +00: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-19 19:27:44 +00:00
|
|
|
*URLconf*; see :doc:`/topics/http/urls` for instructions.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
Returning errors
|
|
|
|
================
|
|
|
|
|
2008-10-24 09:24:42 +00: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-23 22:25:40 +00:00
|
|
|
|
2013-05-18 12:00:52 +00:00
|
|
|
from django.http import HttpResponse, HttpResponseNotFound
|
|
|
|
|
2008-08-23 22:25:40 +00: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 09:24:42 +00: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 12:00:52 +00:00
|
|
|
from django.http import HttpResponse
|
|
|
|
|
2008-10-24 09:24:42 +00:00
|
|
|
def my_view(request):
|
|
|
|
# ...
|
|
|
|
|
|
|
|
# Return a "created" (201) response code.
|
|
|
|
return HttpResponse(status=201)
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
Because 404 errors are by far the most common HTTP error, there's an easier way
|
|
|
|
to handle those errors.
|
|
|
|
|
|
|
|
The Http404 exception
|
|
|
|
---------------------
|
|
|
|
|
2010-11-17 20:03:15 +00:00
|
|
|
.. class:: django.http.Http404()
|
|
|
|
|
2010-11-26 16:53:38 +00: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-23 22:25:40 +00: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
|
2013-05-18 12:00:52 +00:00
|
|
|
from django.shortcuts import render_to_response
|
|
|
|
from polls.models import Poll
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
def detail(request, poll_id):
|
|
|
|
try:
|
|
|
|
p = Poll.objects.get(pk=poll_id)
|
|
|
|
except Poll.DoesNotExist:
|
|
|
|
raise Http404
|
|
|
|
return render_to_response('polls/detail.html', {'poll': p})
|
|
|
|
|
|
|
|
In order to use the ``Http404`` exception to its fullest, you should create a
|
|
|
|
template that is displayed when a 404 error is raised. This template should be
|
|
|
|
called ``404.html`` and located in the top level of your template tree.
|
|
|
|
|
2011-09-11 04:01:41 +00:00
|
|
|
.. _customizing-error-views:
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
Customizing error views
|
|
|
|
=======================
|
|
|
|
|
2012-08-20 13:01:57 +00:00
|
|
|
.. _http_not_found_view:
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
The 404 (page not found) view
|
|
|
|
-----------------------------
|
|
|
|
|
2013-01-01 13:12:42 +00:00
|
|
|
.. function:: django.views.defaults.page_not_found(request, template_name='404.html')
|
|
|
|
|
2013-08-01 22:07:59 +00:00
|
|
|
When you raise :exc:`~django.http.Http404` from within a view, Django loads a
|
|
|
|
special view devoted to handling 404 errors. By default, it's the view
|
|
|
|
:func:`django.views.defaults.page_not_found`, which either produces a very
|
|
|
|
simple "Not Found" message or loads and renders the template ``404.html`` if
|
|
|
|
you created it in your root template directory.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2012-09-30 21:16:14 +00:00
|
|
|
The default 404 view will pass one variable to the template: ``request_path``,
|
|
|
|
which is the URL that resulted in the error.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2011-06-25 12:39:48 +00:00
|
|
|
The ``page_not_found`` view should suffice for 99% of Web applications, but if
|
2013-09-22 14:21:09 +00:00
|
|
|
you want to override it, you can specify :data:`~django.conf.urls.handler404`
|
|
|
|
in your root URLconf (setting ``handler404`` anywhere else will have no
|
|
|
|
effect), like so::
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
handler404 = 'mysite.views.my_custom_404_view'
|
|
|
|
|
2011-06-25 12:39:48 +00:00
|
|
|
Behind the scenes, Django determines the 404 view by looking for
|
|
|
|
``handler404`` in your root URLconf, and falling back to
|
|
|
|
``django.views.defaults.page_not_found`` if you did not define one.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2012-09-30 21:16:14 +00:00
|
|
|
Three things to note about 404 views:
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* The 404 view is also called if Django doesn't find a match after
|
|
|
|
checking every regular expression in the URLconf.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* The 404 view is passed a :class:`~django.template.RequestContext` and
|
|
|
|
will have access to variables supplied by your
|
|
|
|
:setting:`TEMPLATE_CONTEXT_PROCESSORS` setting (e.g., ``MEDIA_URL``).
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* If :setting:`DEBUG` is set to ``True`` (in your settings module), then
|
|
|
|
your 404 view will never be used, and your URLconf will be displayed
|
|
|
|
instead, with some debug information.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2012-08-20 13:01:57 +00:00
|
|
|
.. _http_internal_server_error_view:
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
The 500 (server error) view
|
|
|
|
----------------------------
|
|
|
|
|
2013-09-22 14:21:09 +00:00
|
|
|
.. function:: django.views.defaults.server_error(request, template_name='500.html')
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
Similarly, Django executes special-case behavior in the case of runtime errors
|
|
|
|
in view code. If a view results in an exception, Django will, by default, call
|
2012-09-30 21:16:14 +00:00
|
|
|
the view ``django.views.defaults.server_error``, which either produces a very
|
|
|
|
simple "Server Error" message or loads and renders the template ``500.html`` if
|
|
|
|
you created it in your root template directory.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2012-09-30 21:16:14 +00:00
|
|
|
The default 500 view passes no variables to the ``500.html`` template and is
|
|
|
|
rendered with an empty ``Context`` to lessen the chance of additional errors.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
This ``server_error`` view should suffice for 99% of Web applications, but if
|
2013-09-22 14:21:09 +00:00
|
|
|
you want to override the view, you can specify
|
|
|
|
:data:`~django.conf.urls.handler500` in your root URLconf, like so::
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
handler500 = 'mysite.views.my_custom_error_view'
|
|
|
|
|
2011-06-25 12:39:48 +00:00
|
|
|
Behind the scenes, Django determines the 500 view by looking for
|
|
|
|
``handler500`` in your root URLconf, and falling back to
|
|
|
|
``django.views.defaults.server_error`` if you did not define one.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2012-09-30 21:16:14 +00:00
|
|
|
One thing to note about 500 views:
|
2011-06-25 12:39:48 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* If :setting:`DEBUG` is set to ``True`` (in your settings module), then
|
|
|
|
your 500 view will never be used, and the traceback will be displayed
|
|
|
|
instead, with some debug information.
|
2011-08-12 14:15:31 +00:00
|
|
|
|
|
|
|
.. _http_forbidden_view:
|
|
|
|
|
|
|
|
The 403 (HTTP Forbidden) view
|
2011-08-13 11:23:13 +00:00
|
|
|
-----------------------------
|
2011-08-12 14:15:31 +00:00
|
|
|
|
2013-09-22 14:21:09 +00:00
|
|
|
.. function:: django.views.defaults.permission_denied(request, template_name='403.html')
|
|
|
|
|
2011-08-12 14:15:31 +00:00
|
|
|
In the same vein as the 404 and 500 views, Django has a view to handle 403
|
|
|
|
Forbidden errors. If a view results in a 403 exception then Django will, by
|
|
|
|
default, call the view ``django.views.defaults.permission_denied``.
|
|
|
|
|
|
|
|
This view loads and renders the template ``403.html`` in your root template
|
|
|
|
directory, or if this file does not exist, instead serves the text
|
2011-09-04 21:17:30 +00:00
|
|
|
"403 Forbidden", as per :rfc:`2616` (the HTTP 1.1 Specification).
|
2011-08-12 14:15:31 +00:00
|
|
|
|
2012-11-03 16:04:53 +00:00
|
|
|
``django.views.defaults.permission_denied`` is triggered by a
|
|
|
|
:exc:`~django.core.exceptions.PermissionDenied` exception. To deny access in a
|
|
|
|
view you can use code like this::
|
|
|
|
|
|
|
|
from django.core.exceptions import PermissionDenied
|
|
|
|
|
|
|
|
def edit(request, pk):
|
|
|
|
if not request.user.is_staff:
|
|
|
|
raise PermissionDenied
|
|
|
|
# ...
|
|
|
|
|
2011-08-12 14:15:31 +00:00
|
|
|
It is possible to override ``django.views.defaults.permission_denied`` in the
|
2013-09-22 14:21:09 +00:00
|
|
|
same way you can for the 404 and 500 views by specifying a
|
|
|
|
:data:`~django.conf.urls.handler403` in your root URLconf::
|
2011-08-12 14:15:31 +00:00
|
|
|
|
|
|
|
handler403 = 'mysite.views.my_custom_permission_denied_view'
|
2013-05-15 23:14:28 +00:00
|
|
|
|
|
|
|
.. _http_bad_request_view:
|
|
|
|
|
|
|
|
The 400 (bad request) view
|
|
|
|
--------------------------
|
|
|
|
|
2013-09-22 14:21:09 +00:00
|
|
|
.. versionadded:: 1.6
|
|
|
|
|
|
|
|
.. function:: django.views.defaults.bad_request(request, template_name='400.html')
|
|
|
|
|
2013-05-15 23:14:28 +00:00
|
|
|
When a :exc:`~django.core.exceptions.SuspiciousOperation` is raised in Django,
|
2013-09-22 14:21:09 +00:00
|
|
|
it may be handled by a component of Django (for example resetting the session
|
|
|
|
data). If not specifically handled, Django will consider the current request a
|
|
|
|
'bad request' instead of a server error.
|
2013-05-15 23:14:28 +00:00
|
|
|
|
2013-09-22 14:21:09 +00:00
|
|
|
``django.views.defaults.bad_request``, is otherwise very similar to the
|
|
|
|
``server_error`` view, but returns with the status code 400 indicating that
|
2013-05-15 23:14:28 +00:00
|
|
|
the error condition was the result of a client operation.
|
|
|
|
|
2013-09-22 14:21:09 +00:00
|
|
|
Like ``server_error``, the default ``bad_request`` should suffice for
|
2013-05-15 23:14:28 +00:00
|
|
|
99% of Web applications, but if you want to override the view, you can specify
|
2013-09-22 14:21:09 +00:00
|
|
|
:data:`~django.conf.urls.handler400` in your root URLconf, like so::
|
2013-05-15 23:14:28 +00:00
|
|
|
|
|
|
|
handler400 = 'mysite.views.my_custom_bad_request_view'
|
|
|
|
|
|
|
|
``bad_request`` views are also only used when :setting:`DEBUG` is ``False``.
|