---
title: "django.urls 实用函数"
version: 6.0
locale: zh-hans
source: https://docs.djangoproject.com/zh-hans/6.0/ref/urlresolvers/
canonical: https://djangodocs.dev/zh-hans/6.0/ref/urlresolvers/
---
# `django.urls` 实用函数

## reverse()

The `reverse()` function can be used to return an absolute path reference
for a given view and optional parameters, similar to the [`url`](/zh-hans/6.0/ref/templates/builtins/#std-templatetag-url) tag:

#### `reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None, * (Keyword-only parameters separator (PEP 3102)), query=None, fragment=None)`

`viewname` can be a [URL pattern name](/zh-hans/6.0/topics/http/urls/#naming-url-patterns) or the
callable view object used in the URLconf. For example, given the following
`url`:

```
from news import views

path("archive/", views.archive, name="news-archive")
```

你可以使用以下任何一种方式来反查 URL：

```
# using the named URL
reverse("news-archive")

# passing a callable object
# (This is discouraged because you can't reverse namespaced views this way.)
from news import views

reverse(views.archive)
```

如果 URL 接受参数，你可以在 `args` 中传递参数。例如：

```
from django.urls import reverse

def myview(request):
    return HttpResponseRedirect(reverse("arch-summary", args=[1945]))
```

你也可以传递 `kwargs` 而不是 `args`。例如：

```pycon
>>> reverse("admin:app_list", kwargs={"app_label": "auth"})
'/admin/auth/'
```

`args` 和 `kwargs` 不能同时传递给 `reverse()`。

如果不能匹配，`reverse()` 会引发一个 [`NoReverseMatch`](/zh-hans/6.0/ref/exceptions/#django.urls.NoReverseMatch) 异常。

`reverse()` 函数可以反查 URL 的多种正则表达式模式，但不是每一种可能的模式。目前主要的限制是，模式不能包含使用竖条（`"|"`）字符的替代选择。你可以很高兴地使用这样的模式与传入的 URL 进行匹配，并将它们发送给视图，但你不能反查这样的模式。

`current_app` 参数允许你向解析器提供一个提示，说明当前执行的视图属于哪个应用程序。这个 `current_app` 参数被用作提示，以便根据 [命名空间的 URL 解析策略](/zh-hans/6.0/topics/http/urls/#topics-http-reversing-url-namespaces)，将应用程序名称空间解析为特定应用程序实例上的 URL。

`urlconf` 参数是 URLconf 模块，其中包含用于反查的 URL 模式。默认情况下，使用的是当前线程的根 URLconf。

The `query` keyword argument specifies parameters to be added to the returned
URL. It can accept an instance of [`QueryDict`](/zh-hans/6.0/ref/request-response/#django.http.QueryDict) (such as
`request.GET`) or any value compatible with [`urllib.parse.urlencode()`](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode).
The encoded query string is appended to the resolved URL, prefixed by a `?`.

The `fragment` keyword argument specifies a fragment identifier to be
appended to the returned URL (that is, after the path and query string,
preceded by a `#`).

例如：

```pycon
>>> from django.urls import reverse
>>> reverse("admin:index", query={"q": "biscuits", "page": 2}, fragment="results")
'/admin/?q=biscuits&page=2#results'
>>> reverse("admin:index", query=[("color", "blue"), ("color", 1), ("none", None)])
'/admin/?color=blue&color=1&none=None'
>>> reverse("admin:index", query={"has empty spaces": "also has empty spaces!"})
'/admin/?has+empty+spaces=also+has+empty+spaces%21'
>>> reverse("admin:index", fragment="no encoding is done")
'/admin/#no encoding is done'
```

> **Changed in Django 5.2**
>
> The `query` and `fragment` arguments were added.

> **Note**
>
> `reverse()` 返回的字符串已经被 [urlquoted](/zh-hans/6.0/ref/unicode/#uri-and-iri-handling)。例如：
>
> ```pycon
> >>> reverse("cities", args=["Orléans"])
> '.../Orl%C3%A9ans/'
> ```
>
> 对 `reverse()` 的输出应用进一步的编码（如 [`urllib.parse.quote()`](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote)）可能会产生不理想的结果。

> **按视图对象反转基于类的视图**
>
> The view object can also be the result of calling
> [`as_view()`](/zh-hans/6.0/ref/class-based-views/base/#django.views.generic.base.View.as_view) if the same view object is
> used in the URLConf. Following the original example, the view object could
> be defined as:
>
> *`news/views.py`*
>
> ```python
>  from django.views import View
>
>
>  class ArchiveView(View): ...
>
>
>  archive = ArchiveView.as_view()
> ```
>
> 但是，请记住，命名空间视图不能按视图对象反转。

## `reverse_lazy()`

[reverse()](#reverse) 的惰性执行版本。

#### `reverse_lazy(viewname, urlconf=None, args=None, kwargs=None, current_app=None, * (Keyword-only parameters separator (PEP 3102)), query=None, fragment=None)`

当你需要在你的项目的 URLConf 被加载之前使用 URL 反查时，这个功能很有用。一些常见的需要使用该功能的情况是：

- 提供一个反查的 URL 作为基于类的通用视图的 `url` 属性。
- 为装饰器提供一个反查的 URL（例如 [`django.contrib.auth.decorators.permission_required()`](/zh-hans/6.0/topics/auth/default/#django.contrib.auth.decorators.permission_required) 装饰器的 `login_url` 参数）。
- 提供一个反查的 URL 作为函数签名中参数的默认值。

> **Changed in Django 5.2**
>
> The `query` and `fragment` arguments were added.

## `resolve()`

`resolve()` 函数可用于解析到相应视图函数的 URL 路径。该函数的签名如下：

#### `resolve(path, urlconf=None)`

`path` 是你要解析的 URL 路径。与 [`reverse()`](#django.urls.reverse) 一样，你不需要担心 `urlconf` 参数。该函数返回一个 [`ResolverMatch`](#django.urls.ResolverMatch) 对象，允许你访问关于解析 URL 的各种元数据。

如果 URL 没有解析，函数会引发一个 [`Resolver404`](/zh-hans/6.0/ref/exceptions/#django.urls.Resolver404) 异常（[`Http404`](/zh-hans/6.0/topics/http/views/#django.http.Http404) 的一个子类）。

#### `class ResolverMatch`

#### `func`

用于服务 URL 的视图函数。

#### `args`

从 URL 中解析出的传递给视图函数的参数。

#### `kwargs`

所有将传递给视图函数的关键字参数，即 [`captured_kwargs`](#django.urls.ResolverMatch.captured_kwargs) 和 [`extra_kwargs`](#django.urls.ResolverMatch.extra_kwargs)。

#### `captured_kwargs`

从 URL 解析出的将传递给视图函数的捕获关键字参数。

#### `extra_kwargs`

将传递给视图函数的额外关键字参数。

#### `url_name`

与 URL 匹配的 URL 模式的名称。

#### `route`

匹配 URL 模式的路径。

例如，如果 ```path('users/<id>/', ...)``是匹配的模式，``route``` 将包含 `'users/<id>/'`。

#### `tried`

在 URL 匹配一个模式或耗尽可用模式之前尝试的 URL 模式列表。

#### `app_name`

匹配 URL 模式的应用程序命名空间。

#### `app_names`

匹配 URL 模式的完整应用程序命名空间中的单个命名空间组件列表。例如，如果 `app_name` 是 `'foo:bar'`，那么 `app_names` 将是 `['foo', 'bar']`。

#### `namespace`

匹配 URL 模式的实例命名空间。

#### `namespaces`

匹配 URL 模式的完整实例命名空间中的单个命名空间组件列表，即，如果命名空间是 `foo:bar`，那么命名空间将是 `['foo'，'bar']`。

#### `view_name`

匹配 URL 的视图名称，包括命名空间（如果有的话）。

然后可以查询一个 [`ResolverMatch`](#django.urls.ResolverMatch) 对象，以提供与 URL 相匹配的 URL 模式的信息：

```
# Resolve a URL
match = resolve("/some/path/")
# Print the URL pattern that matches the URL
print(match.url_name)
```

一个 [`ResolverMatch`](#django.urls.ResolverMatch) 对象也可以解包为以下三个：

```
func, args, kwargs = resolve("/some/path/")
```

[`resolve()`](#django.urls.resolve) 的一个可能的用法是测试一个视图在重定向到它之前是否会引发 `Http404` 错误：

```
from urllib.parse import urlsplit
from django.urls import resolve
from django.http import Http404, HttpResponseRedirect

def myview(request):
    next = request.META.get("HTTP_REFERER", None) or "/"
    response = HttpResponseRedirect(next)

    # modify the request and response as required, e.g. change locale
    # and set corresponding locale cookie

    view, args, kwargs = resolve(urlsplit(next).path)
    kwargs["request"] = request
    try:
        view(*args, **kwargs)
    except Http404:
        return HttpResponseRedirect("/")
    return response
```

## `get_script_prefix()`

#### `get_script_prefix()`

通常，你应该始终使用 [`reverse()`](#django.urls.reverse) 来定义应用程序中的 URL。然而，如果你的应用程序自己构建了 URL 层次结构的一部分，偶尔可能需要生成 URL。在这种情况下，你需要能够找到 Django 项目在其 Web 服务器内的基本 URL（通常，[`reverse()`](#django.urls.reverse) 会为你处理这个）。在这种情况下，你可以调用 `get_script_prefix()`，它将返回你的 Django 项目的 URL 的脚本前缀部分。如果你的 Django 项目位于其 Web 服务器的根目录，这将始终是 `"/"`。

> **Warning**
>
> 此函数 **不能** 在请求-响应周期之外使用，因为它依赖于在该周期期间初始化的值。
