Django 1.8 official document translation: 3-1-2 compilation view


Authoring views

A view function, or simply called view, is a simple Python function that accepts a web request and returns a Web response. The response can be HTML content of a web page, a redirect, a 404 error, an XML document, or a picture… Anything. No matter what logic the view itself contains, a response is returned. It doesn’t matter where the code is written, as long as it’s under your Python directory. In addition, there are no more requirements – it can be said that “there is no magical place”. In order to put the code somewhere, the Convention is to put the view in a file called views. Py, and then put it in your project or application directory.

A simple view

The following is a view that returns the current date and time as an HTML document:

from django.http import HttpResponse
import datetime

def current_datetime(request):
    now =
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)

Let’s read the above code line by line:

  • First, we imported the httpresponse class and Python’s datetime library from the Django. HTTP module.

  • Next, we define current_ Datetime function. It is a view function. Each view function should receive the httprequest object as the first parameter, which is generally called request.

  • Note that the name of the view function is not important; There is no need to name it in a unified way so that Django can recognize it. We named it current_ Datetime, because the name can accurately reflect its function.

  • This view will return an httpresponse object containing the generated response. Each view function returns an httpresponse object. (there are exceptions, which we will talk about next.)

Time zone in Django

Django contains a time_ Zone setting, the default is America / Chicago. It may not be where you live, so you may modify it in the settings file.

Map your URL to the view

So, again, the view function returns an HTML page containing the current date and time. You need to create urlconf to display this view at a specific URL; See URL distributor for details.

Return error

It is quite easy to return HTTP errors in Django. Some subclasses of httpresponse represent HTTP status codes that are not 200 (“OK”). You can find all available subclasses in the request / response document. You can return an instance of those subclasses instead of the ordinary httpresponse to represent an error. For example:

from django.http import HttpResponse, HttpResponseNotFound

def my_view(request):
    # ...
    if foo:
        return HttpResponseNotFound('<h1>Page not found</h1>')
        return HttpResponse('<h1>Page was found</h1>')

Because some status codes are not commonly used, not every status code has a specialized subclass. However, as stated in the httpresponse document, you can also pass the HTTP status code to the httpresponse constructor to create the return class of any status code you want. For example:

from django.http import HttpResponse

def my_view(request):
    # ...

    # Return a "created" (201) response code.
    return HttpResponse(status=201)

Since 404 error is the most common HTTP error, the way to handle this error is very convenient.

Http404 exception

class django.http.Http404

When you return an error such as httpresponsenotfound, it will output the HTML of the error page as the result:

return HttpResponseNotFound('<h1>Page not found</h1>')

For convenience, and because it’s a good idea for your site to have a consistent 404 page, Django provides an http404 exception. If you throw an http404 exception anywhere in the view function, Django will catch it and return to the standard error page of your application with an HTTP 404 error code.

like this:

from django.http import Http404
from django.shortcuts import render_to_response
from polls.models import Poll

def detail(request, poll_id):
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404("Poll does not exist")
    return render_to_response('polls/detail.html', {'poll': p})

In order to make the most of http404, you should create a template to show when 404 errors occur. This template should be called 404. HTML and at the top of your template tree.

If you provide a message when throwing an http404 exception, it will appear in the display of the standard 404 template when debug is true. You can use these messages for debugging; But they usually do not apply to the 404 template itself.

Custom error view

The default error view in Django is sufficient for most web applications, but if you need any custom behavior, it’s easy to rewrite it. Just specify the following processors in your urlconf (setting them anywhere else won’t work).

Handler404 covers the page_ not_ Found view:

handler404 = 'mysite.views.my_custom_page_not_found_view'

Handler500 covers the server_ Error () view:

handler500 = 'mysite.views.my_custom_error_view'

Handler 403 overrides permission_ Denied () view:

handler403 = 'mysite.views.my_custom_permission_denied_view'

Handler 400 covers bad_ Request () view:

handler400 = 'mysite.views.my_custom_bad_request_view'

translator:Flying dragon, Original:View functions

In this paperCC BY-NC-SA 3.0Please keep the author’s signature and the source of the article.

Django document collaborative translation teamThere is a shortage of staff. Interested friends can join us. It is completely public welfare. Communication group: 467338606.

If you think the article is good, you can scan the QR code below to reward me.

Django 1.8 official document translation: 3-1-2 compilation view