Writing views
Here's a view that returns the current date and time, as an HTML document:
Let's step through this code one line at a time:
First, we import the class
HttpResponse
from the module, along with Python'sdatetime
library.Next, we define a function called
current_datetime
. This is the viewfunction. Each view function takes anHttpRequest
object as its first parameter, which is typically namedrequest
.
Note that the name of the view function doesn't matter; it doesn't have tobe named in a certain way in order for Django to recognize it. We'recalling it current_datetime
here, because that name clearly indicateswhat it does.
- The view returns an object thatcontains the generated response. Each view function is responsible forreturning an
HttpResponse
object. (There areexceptions, but we'll get to those later.)
Django's Time Zone
Django includes a setting that defaults toAmerica/Chicago
. This probably isn't where you live, so you might wantto change it in your settings file.
Returning HTTP error codes in Django is easy. There are subclasses of for a number of common HTTP status codesother than 200 (which means "OK"). You can find the full list of availablesubclasses in the documentation. Just return an instance of one of those subclasses instead ofa normal HttpResponse
in order to signify an error. Forexample:
- from django.http import HttpResponse, HttpResponseNotFound
- def my_view(request):
- if foo:
- return HttpResponseNotFound('<h1>Page not found</h1>')
- else:
- return HttpResponse('<h1>Page was found</h1>')
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 inthe documentation, you can also pass theHTTP status code into the constructor for HttpResponse
to create a return class for any status code you like. For example:
- from django.http import HttpResponse
- def my_view(request):
- # ...
- # Return a "created" (201) response code.
- return HttpResponse(status=201)
Because 404 errors are by far the most common HTTP error, there's an easier wayto handle those errors.
- class
django.http.
Http404
For convenience, and because it's a good idea to have a consistent 404 error pageacross your site, Django provides an Http404
exception. If you raiseHttp404
at any point in a view function, Django will catch it and return thestandard error page for your application, along with an HTTP error code 404.
Example usage:
- from django.http import Http404
- from django.shortcuts import render
- from polls.models import Poll
- def detail(request, poll_id):
- try:
- p = Poll.objects.get(pk=poll_id)
- except Poll.DoesNotExist:
- raise Http404("Poll does not exist")
- return render(request, 'polls/detail.html', {'poll': p})
In order to show customized HTML when Django returns a 404, you can create anHTML template named 404.html
and place it in the top level of yourtemplate tree. This template will then be served when DEBUG
is setto False
.
When is True
, you can provide a message to Http404
andit will appear in the standard 404 debug template. Use these messages fordebugging purposes; they generally aren't suitable for use in a production 404template.
The page_not_found()
view is overridden by:
- handler404 = 'mysite.views.my_custom_page_not_found_view'
The server_error()
view is overridden by:
The permission_denied()
view is overridden by:
- handler403 = 'mysite.views.my_custom_permission_denied_view'
The bad_request()
view is overridden by:
参见
Use the CSRF_FAILURE_VIEW
setting to override the CSRF errorview.
Testing custom error views
To test the response of a custom error handler, raise the appropriate exceptionin a test view. For example: