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's datetime library.

    • Next, we define a function called current_datetime. This is the viewfunction. Each view function takes an HttpRequestobject as its first parameter, which is typically named request.

    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:

    1. from django.http import HttpResponse, HttpResponseNotFound
    2.  
    3. def my_view(request):
    4. if foo:
    5. return HttpResponseNotFound('<h1>Page not found</h1>')
    6. else:
    7. 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 HttpResponseto create a return class for any status code you like. For example:

    1. from django.http import HttpResponse
    2.  
    3. def my_view(request):
    4. # ...
    5.  
    6. # Return a "created" (201) response code.
    7. 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:

    1. from django.http import Http404
    2. from django.shortcuts import render
    3. from polls.models import Poll
    4.  
    5. def detail(request, poll_id):
    6. try:
    7. p = Poll.objects.get(pk=poll_id)
    8. except Poll.DoesNotExist:
    9. raise Http404("Poll does not exist")
    10. 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:

    1. handler404 = 'mysite.views.my_custom_page_not_found_view'

    The server_error() view is overridden by:

    The permission_denied() view is overridden by:

    1. 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: