Built-in Views

Several of Django's built-in views are documented inWriting views as well as elsewhere in the documentation.

Serving files in development

  • static.serve(request, path, document_root, show_indexes=False)
  • There may be files other than your project's static assets that, forconvenience, you'd like to have Django serve for you in local development.The serve() view can be used to serve any directoryyou give it. (This view is not hardened for production use and should beused only as a development aid; you should serve these files in productionusing a real front-end web server).

The most likely example is user-uploaded content in MEDIA_ROOT.django.contrib.staticfiles is intended for static assets and has nobuilt-in handling for user-uploaded files, but you can have Django serve yourMEDIA_ROOT by appending something like this to your URLconf:

  1. from django.conf import settings
  2. from django.urls import re_path
  3. from django.views.static import serve
  4.  
  5. # ... the rest of your URLconf goes here ...
  6.  
  7. if settings.DEBUG:
  8. urlpatterns += [
  9. re_path(r'^media/(?P<path>.*)$', serve, {
  10. 'document_root': settings.MEDIA_ROOT,
  11. }),
  12. ]

Note, the snippet assumes your MEDIA_URL has a value of'/media/'. This will call the serve() view,passing in the path from the URLconf and the (required) document_rootparameter.

Since it can become a bit cumbersome to define this URL pattern, Djangoships with a small URL helper function static()that takes as parameters the prefix such as MEDIA_URL and a dottedpath to a view, such as 'django.views.static.serve'. Any other functionparameter will be transparently passed to the view.

错误的视图

Django comes with a few views by default for handling HTTP errors. To overridethese with your own custom views, see Customizing error views.

404 (page not found) 视图

  • defaults.pagenot_found(_request, exception, template_name='404.html')
  • When you raise Http404 from within a view, Django loads aspecial view devoted to handling 404 errors. By default, it's the viewdjango.views.defaults.page_not_found(), which either produces a verysimple "Not Found" message or loads and renders the template 404.html ifyou created it in your root template directory.

The default 404 view will pass two variables to the template: request_path,which is the URL that resulted in the error, and exception, which is auseful representation of the exception that triggered the view (e.g. containingany message passed to a specific Http404 instance).

关于404视图需要注意的三个要点:

  • The 404 view is also called if Django doesn't find a match afterchecking every regular expression in the URLconf.
  • The 404 view is passed a RequestContext andwill have access to variables supplied by your template contextprocessors (e.g. MEDIA_URL).
  • 如果 DEBUG 设置为True(在您的配置模块中),那么您的404视图将永远不会被使用,作为替代,你的URL配置与一些调试信息将会被显示。

The 500 (server error) view

  • defaults.servererror(_request, template_name='500.html')
  • 同样,Django在视图代码中执行错误时会执行特殊行为。如果视图导致异常,Django默认会调用视图django.views.defaults.server_error,这会产生一个非常简单的“服务器错误”消息,或者如果您在根模板目录中创建了“500.html”,则会加载并渲染它。

默认的500视图不会将变量传递给500.html模板,并使用空的Context渲染以减少出现附加错误的可能性。

如果 DEBUG 设置为True(在您的配置模块中),那么您的500视图将永远不会被使用,作为替代,调用回溯与一些调试信息将会被显示。

403 (HTTP Forbidden) 视图

  • defaults.permissiondenied(_request, exception, template_name='403.html')
  • 与404和500视图一样,Django有处理403 Forbidden错误的视图。如果视图导致403异常,那么Django默认会调用视图django.views.defaults.permission_denied

这个视图从你的根模板目录加载和渲染 403.html 模板,如果这个文件不存在将会显示“403 Forbidden”,按照 RFC 7231#section-6.5.3 (HTTP 1.1 规范)。 模板上下文包含 exception,它是触发视图的异常的字符串表示形式。

django.views.defaults.permission_denied is triggered by aPermissionDenied exception. To deny access in aview you can use code like this:

  1. from django.core.exceptions import PermissionDenied
  2.  
  3. def edit(request, pk):
  4. if not request.user.is_staff:
  5. raise PermissionDenied
  6. # ...

400 (bad request) 视图

  • defaults.badrequest(_request, exception, template_name='400.html')
  • When a SuspiciousOperation is raised in Django,it may be handled by a component of Django (for example resetting the sessiondata). If not specifically handled, Django will consider the current request a'bad request' instead of a server error.

django.views.defaults.bad_request, is otherwise very similar to theserver_error view, but returns with the status code 400 indicating thatthe error condition was the result of a client operation. By default, nothingrelated to the exception that triggered the view is passed to the templatecontext, as the exception message might contain sensitive information likefilesystem paths.

bad_request视图也仅在以下情况下使用 :setting:`DEBUG` 为False