---
title: "内置视图"
version: 6.0
locale: zh-hans
source: https://docs.djangoproject.com/zh-hans/6.0/ref/views/
canonical: https://djangodocs.dev/zh-hans/6.0/ref/views/
---
# 内置视图

Django 内置的几个视图在 [编写视图](/zh-hans/6.0/topics/http/views/) 以及文档的其他地方都有记载。

## 为开发中的文件提供服务

#### `static.serve(request, path, document_root, show_indexes=False)`

除了你的项目的静态资源外，可能还有一些其他的文件，为了方便，你想让 Django 在本地开发中为你提供服务。[`serve()`](#django.views.static.serve) 视图可以用来为你给它的任何目录提供服务。（这个视图并 **没有** 强到用于生产，只应该作为开发辅助工具，你应该在生产中使用真正的前端 Web 服务器来服务这些文件）。

最有可能的例子是用户在 [`MEDIA_ROOT`](/zh-hans/6.0/ref/settings/#std-setting-MEDIA_ROOT) 中上传的内容。`django.contrib.staticfiles` 是为静态资源设计的，并没有内置处理用户上传文件的功能，但是你可以通过在 URLconf 中添加这样的内容，让 Django 为你的 [`MEDIA_ROOT`](/zh-hans/6.0/ref/settings/#std-setting-MEDIA_ROOT) 服务：

```
from django.conf import settings
from django.urls import re_path
from django.views.static import serve

# ... the rest of your URLconf goes here ...

if settings.DEBUG:
    urlpatterns += [
        re_path(
            r"^media/(?P<path>.*)$",
            serve,
            {
                "document_root": settings.MEDIA_ROOT,
            },
        ),
    ]
```

请注意，这段代码假定您的 [`MEDIA_URL`](/zh-hans/6.0/ref/settings/#std-setting-MEDIA_URL) 的值是 `'media/'`。它将调用 [`serve()`](#django.views.static.serve) 视图，传递 URLconf 中的路径和（必需的） `document_root` 参数。

由于定义这种 URL 模式可能会变得有点麻烦，Django 提供了一个小的 URL 辅助函数 [`static()`](/zh-hans/6.0/ref/urls/#django.conf.urls.static.static)，它的参数是前缀，如 [`MEDIA_URL`](/zh-hans/6.0/ref/settings/#std-setting-MEDIA_URL) 和一个指向视图的点分隔路径，如 `'django.views.static.service'`。其他任何函数参数都将透明地传递给视图。

## 错误视图

Django 默认提供了一些处理 HTTP 错误的视图。要用你自己的自定义视图覆盖这些视图，请参见 [自定义报错视图](/zh-hans/6.0/topics/http/views/#customizing-error-views)。

### 404（页面没有找到)）视图

#### `defaults.page_not_found(request, exception, template_name='404.html')`

当你在视图中提出 [`Http404`](/zh-hans/6.0/topics/http/views/#django.http.Http404) 时，Django 会加载一个专门处理 404 错误的视图。默认情况下，它是视图 [`django.views.defaults.page_not_found()`](#django.views.defaults.page_not_found)，如果你在根模板目录下创建了模板 `404.html`，那么它要么产生“Not Found”消息，要么加载并渲染它。

默认的 404 视图将向模板传递两个变量：`request_path`，这是导致错误的 URL，和 `exception`，这是触发视图的异常的有用表示（例如，包含传递给特定 `Http404` 实例的任何消息）。

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

- 如果 Django 在检查了 URLconf 中的每一个正则表达式后都没有找到匹配的结果，也会调用 404 视图。
- 404 视图被传递了一个 [`RequestContext`](/zh-hans/6.0/ref/templates/api/#django.template.RequestContext)，并且将可以访问由你的模板上下文处理器提供的变量（例如 `MEDIA_URL`）。
- 如果 [`DEBUG`](/zh-hans/6.0/ref/settings/#std-setting-DEBUG) 设置为 `True` （在你的配置模块中），那么你的 404 视图将永远不会被使用，而你的 URLconf 将被显示，并附带一些调试信息。

### 500（服务器错误）视图

#### `defaults.server_error(request, template_name='500.html')`

同样，在视图代码出现运行时错误的情况下，Django 也会执行特定行为。如果一个视图出现异常，Django 默认会调用视图 `django.views.defaults.server_error`，如果你在根模板目录下创建了模板 `500.html`，则会产生一个“Server Error”消息或加载并渲染模板 `500.html`。

默认的 500 视图不向 `500.html` 模板传递任何变量，并以一个空的 `Context` 呈现，以减少额外错误的机会。

如果 [`DEBUG`](/zh-hans/6.0/ref/settings/#std-setting-DEBUG) 被设置为 `True` （在你的配置模块中），那么你的 500 视图将永远不会被使用，而会显示一些调试信息的回溯。

### 403（HTTP 禁止）视图

#### `defaults.permission_denied(request, exception, template_name='403.html')`

与 404 和 500 视图一样，Django 也有一个视图来处理 403 禁止错误。如果一个视图出现 403 异常，那么 Django 默认会调用视图 `django.views.defaults.permission_denied`。

此视图加载并呈现您根模板目录中的模板 `403.html`，如果此文件不存在，则根据 [**RFC 9110 Section 15.5.4**](https://datatracker.ietf.org/doc/html/rfc9110.html#section-15.5.4) （HTTP 1.1 规范）提供文本 "403 Forbidden"。模板上下文包含 `exception`，它是触发视图的异常的字符串表示形式。

`django.views.defaults.permission_denied` 由一个 [`PermissionDenied`](/zh-hans/6.0/ref/exceptions/#django.core.exceptions.PermissionDenied) 异常触发。要拒绝一个视图的访问，你可以使用这样的代码：

```
from django.core.exceptions import PermissionDenied

def edit(request, pk):
    if not request.user.is_staff:
        raise PermissionDenied
    # ...
```

### 400（错误请求）视图

#### `defaults.bad_request(request, exception, template_name='400.html')`

Similarly, Django has a view to handle 400 Bad Request errors.

This view either produces a "Bad Request" message or loads and renders the
template `400.html` if you created it in your root template directory.
It returns with status code 400 indicating that the error condition was the
result of a client operation. By default, nothing related to the exception that
triggered the view is passed to the template context, as the exception message
might contain sensitive information like filesystem paths.

`django.views.defaults.bad_request` is triggered by a
[`BadRequest`](/zh-hans/6.0/ref/exceptions/#django.core.exceptions.BadRequest) exception. Also, when a
[`SuspiciousOperation`](/zh-hans/6.0/ref/exceptions/#django.core.exceptions.SuspiciousOperation) is raised in Django,
it may be handled by a component of Django (for example resetting the session
data). If not specifically handled, Django will consider the current request a
'bad request' instead of a server error, and handle it with `bad_request`.

`bad_request` 视图也只有在 `` DEBUG` `` 为 `False` 时才能使用。
