---
title: "URLconfs 中使用的 django.urls 函数"
version: 3.1
locale: zh-hans
source: https://docs.djangoproject.com/zh-hans/3.1/ref/urls/
canonical: https://djangodocs.dev/zh-hans/3.1/ref/urls/
---
# URLconfs 中使用的 `django.urls` 函数

## `path()`

#### `path(route, view, kwargs=None, name=None)`

返回一个元素，以便包含在 `urlpatterns` 中。例如：

```
from django.urls import include, path

urlpatterns = [
    path('index/', views.index, name='main-view'),
    path('bio/<username>/', views.bio, name='bio'),
    path('articles/<slug:title>/', views.article, name='article-detail'),
    path('articles/<slug:title>/<int:section>/', views.section, name='article-section'),
    path('weblog/', include('blog.urls')),
    ...
]
```

`route` 参数应该是一个字符串或 [`gettext_lazy()`](/zh-hans/3.1/ref/utils/#django.utils.translation.gettext_lazy) （参见 [翻译URL模式](/zh-hans/3.1/topics/i18n/translation/#translating-urlpatterns)），它包含一个 URL 模式。这个字符串可以包含角括号（就像上面的 `<username>`）来捕获 URL 的一部分，并将其作为关键字参数发送给视图。角括号可以包含一个转换器规格（像 `<int:section>` 的 `int` 部分），它限制了匹配的字符，也可以改变传递给视图的变量的类型。例如，`<int:section>` 匹配一串十进制数字，并将值转换为 `int`。更多细节请参见 [Django 如何处理一个请求](/zh-hans/3.1/topics/http/urls/#how-django-processes-a-request)。

`view` 参数是一个视图函数或 [`as_view()`](/zh-hans/3.1/ref/class-based-views/base/#django.views.generic.base.View.as_view) 的结果，用于基于类的视图。它也可以是一个 [`django.urls.include()`](#django.urls.include)。

`kwargs` 参数允许你向视图函数或方法传递附加参数。参见 [传递额外选项给视图函数](/zh-hans/3.1/topics/http/urls/#views-extra-options) 的例子。

关于为什么 `name` 参数是有用的，请参见 [命名 URL 模式](/zh-hans/3.1/topics/http/urls/#naming-url-patterns)。

## `re_path()`

#### `re_path(route, view, kwargs=None, name=None)`

返回一个元素，以便包含在 `urlpatterns` 中。例如：

```
from django.urls import include, re_path

urlpatterns = [
    re_path(r'^index/$', views.index, name='index'),
    re_path(r'^bio/(?P<username>\w+)/$', views.bio, name='bio'),
    re_path(r'^weblog/', include('blog.urls')),
    ...
]
```

`route` 参数应该是一个字符串或 [`gettext_lazy()`](/zh-hans/3.1/ref/utils/#django.utils.translation.gettext_lazy) （参见 [翻译URL模式](/zh-hans/3.1/topics/i18n/translation/#translating-urlpatterns)），它包含一个与 Python 的 [`re`](https://docs.python.org/3/library/re.html#module-re) 模块兼容的正则表达式。字符串通常使用原始字符串语法（`r''`），因此它们可以包含像 `/d` 这样的序列，而不需要用另一个反斜杠来转义。当进行匹配时，从正则表达式中捕获的组会被传递到视图中 —— 如果组是命名的，则作为命名的参数，否则作为位置参数。值以字符串的形式传递，不进行任何类型转换。

When a `route` ends with `$` the whole requested URL, matching against
[`path_info`](/zh-hans/3.1/ref/request-response/#django.http.HttpRequest.path_info), must match the regular expression
pattern ([`re.fullmatch()`](https://docs.python.org/3/library/re.html#re.fullmatch) is used).

`view`、kwargs\` 和 `name` 参数与 [`path()`](#django.urls.path) 相同。

> **Changed in Django 2.2.25**
>
> In older versions, a full-match wasn't required for a `route` which ends
> with `$`.

## `include()`

#### `include(module, namespace=None)`

#### `include(pattern_list)`

#### `include((pattern_list, app_namespace), namespace=None)`

一个函数，它接收一个完整的 Python 导入路径到另一个应该被 “包含” 在这里的 URLconf 模块。可以选择指定 [application namespace](/zh-hans/3.1/topics/http/urls/#term-application-namespace) 和 [instance namespace](/zh-hans/3.1/topics/http/urls/#term-instance-namespace)，在这两个空间中，条目将被包含进去。

通常，应用程序的命名空间应该由包含的模块指定。如果设置了应用程序命名空间，`namespace` 参数可以用来设置不同的实例命名空间。

`include()` 也接受一个返回 URL 模式的迭代函数或一个包含这种迭代函数加上应用程序名称空间的二元元组作为参数。

**参数:** - `module` -- URLconf 模块（或模块名称）
- `namespace` ([`str`](https://docs.python.org/3/library/stdtypes.html#str)) -- 包含的 URL 条目的实例命名空间。
- `pattern_list` -- 可迭代的 [`path()`](#django.urls.path) 和／或 [`re_path()`](#django.urls.re_path) 实例。
- `app_namespace` ([`str`](https://docs.python.org/3/library/stdtypes.html#str)) -- 被包含的 URL 条目的应用命名空间

参见 [包含其它的URLconfs](/zh-hans/3.1/topics/http/urls/#including-other-urlconfs) 和 [URL 命名空间和包含的 URLconfs](/zh-hans/3.1/topics/http/urls/#namespaces-and-include)。

## `register_converter()`

#### `register_converter(converter, type_name)`

注册一个转换器的函数，用于 [`path()`](#django.urls.path) 的 `route`。

`converter` 参数是一个转换器类，`type_name` 是路径模式中使用的转换器名称。参见 [注册自定义的路径转换器](/zh-hans/3.1/topics/http/urls/#registering-custom-path-converters) 的例子。

# URLconfs 中使用的 `django.conf.urls` 函数

## `static()`

#### `static.static(prefix, view=django.views.static.serve, **kwargs)`

用于返回在调试模式下服务文件的 URL 模式的辅助函数：

```
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
```

## `url()`

#### `url(regex, view, kwargs=None, name=None)`

这个函数是 [`django.urls.re_path()`](#django.urls.re_path) 的别名。

> **Deprecated since Django 3.1**
>
> Deprecated since version 3.1: [`django.urls.re_path()`](#django.urls.re_path) 的别名，以便向后兼容。

## `handler400`

#### `handler400`

一个可调用对象，或者一个代表视图的完整 Python 导入路径的字符串，如果 HTTP 客户端发送了一个引起错误条件的请求，并且响应的状态码为 400，那么就会调用该视图。

默认情况下，这是 [`django.views.defaults.bad_request()`](/zh-hans/3.1/ref/views/#django.views.defaults.bad_request)。如果你实现了自定义视图，请确保它接受 `request` 和 `exception` 参数，并返回一个 [`HttpResponseBadRequest`](/zh-hans/3.1/ref/request-response/#django.http.HttpResponseBadRequest)。

## `handler403`

#### `handler403`

一个可调用对象，或者一个代表视图的完整 Python 导入路径的字符串，如果用户没有访问资源所需的权限，那么就会调用该视图。

默认情况下，这是 [`django.views.defaults.permission_denied()`](/zh-hans/3.1/ref/views/#django.views.defaults.permission_denied)。如果你实现了一个自定义视图，请确保它接受 `request` 和 `exception` 参数，并返回一个 [`HttpResponseForbidden`](/zh-hans/3.1/ref/request-response/#django.http.HttpResponseForbidden)。

## `handler404`

#### `handler404`

一个可调用对象，或者一个代表视图的完整 Python 导入路径的字符串，如果没有任何 URL 模式匹配，那么就会调用该视图。

默认情况下，这是 [`django.views.defaults.page_not_found()`](/zh-hans/3.1/ref/views/#django.views.defaults.page_not_found)。如果你实现了自定义视图，请确保它接受 `request` 和 `exception` 参数，并返回一个 [`HttpResponseNotFound`](/zh-hans/3.1/ref/request-response/#django.http.HttpResponseNotFound)。

## `handler500`

#### `handler500`

一个可调用对象，或者一个代表视图的完整 Python 导入路径的字符串，在服务器出错时会被调用。当你在视图代码中出现运行时错误时，就会发生服务器错误。

默认情况下，这是 [`django.views.defaults.server_error()`](/zh-hans/3.1/ref/views/#django.views.defaults.server_error)。如果你实现了自定义视图，请确保它接受一个 `request` 参数，并返回一个 [`HttpResponseServerError`](/zh-hans/3.1/ref/request-response/#django.http.HttpResponseServerError)。
