编写视图

一个视图函数(或简称为视图)是一个 Python 函数,它接受 Web 请求并返回一个 Web 响应。这个响应可以是 Web 页面的 HTML 内容,或者重定向,或者404错误,或者 XML 文档,或一个图片...或是任何内容。视图本身包含返回响应所需的任何逻辑。这个代码可以存在任何地方,只要它在你的 Python 路径上就行。可以说,不需要其他东西,这里并没有魔法。为了将代码放置在某处,约定将视图放在名为 views.py 的文件里,这个文件放置在项目或应用目录里。

一个简单的视图

这里是一个以 HTML 文档形式返回当前日期和时间的视图:

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)

让我们来完成这个代码:

  • 首先,我们从 django.http 模块导入类 HttpResponse ,以及 Python 的 datetime 库。

  • 然后,我们定义一个名为 current_datetime 的函数。这是一个视图函数。每个视图函数都将 HttpRequest 对象作为第一个参数,通常名为 request

    注意视图函数名称无关紧要;它不需要以特定的名称来让 Django 识别它。我们在这里命名 current_datetime ,因为这个名字可以清楚的表示它的用途。

  • 视图返回一个包含生成的响应的 HttpResponse 对象。每个视图函数都要返回 HttpResponse 对象。(有例外,我们稍后再讲)

Django's Time Zone

Django includes a TIME_ZONE setting that defaults to America/Chicago. This probably isn't where you live, so you might want to change it in your settings file.

Mapping URLs to views

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 URLconf; see URL调度器 for instructions.

Returning errors

Django provides help for returning HTTP error codes. There are subclasses of 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 request/response documentation. Return an instance of one of those subclasses instead of a normal HttpResponse in order to signify an error. For example:

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 in the HttpResponse documentation, you can also pass the HTTP 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 way to handle those errors.

The Http404 exception

class django.http.Http404

When you return an error such as HttpResponseNotFound, you're responsible for defining the HTML of the resulting error page:

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.

用法示例:

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 an HTML template named 404.html and place it in the top level of your template tree. This template will then be served when DEBUG is set to False.

When 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.

Customizing error views

The default error views in Django should suffice for most Web applications, but can easily be overridden if you need any custom behavior. Specify the handlers as seen below in your URLconf (setting them anywhere else will have no effect).

The page_not_found() view is overridden by handler404:

handler404 = 'mysite.views.my_custom_page_not_found_view'

The server_error() view is overridden by handler500:

handler500 = 'mysite.views.my_custom_error_view'

The permission_denied() view is overridden by handler403:

handler403 = 'mysite.views.my_custom_permission_denied_view'

The bad_request() view is overridden by handler400:

handler400 = 'mysite.views.my_custom_bad_request_view'

参见

Use the CSRF_FAILURE_VIEW setting to override the CSRF error view.

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)