“Django/docs/3.0.x/ref/urlresolvers”的版本间差异
(autoload) |
小 (Page commit) |
||
第1行: | 第1行: | ||
+ | {{DISPLAYTITLE:django.urls 实用函数 — Django 文档}} | ||
<div id="module-django.urls" class="section"> | <div id="module-django.urls" class="section"> | ||
<span id="django-urls-utility-functions"></span> | <span id="django-urls-utility-functions"></span> | ||
− | = | + | = django.urls 实用功能 = |
<div id="reverse" class="section"> | <div id="reverse" class="section"> | ||
第8行: | 第9行: | ||
== reverse() == | == reverse() == | ||
− | + | 如果你需要在你的代码中使用类似于 [[#id1|:ttag:`url`]] 模板标签的东西,Django 提供了以下功能: | |
− | ; < | + | ; <span class="sig-name descname"><span class="pre">reverse</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">viewname</span></span>'', ''<span class="n"><span class="pre">urlconf</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">args</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">kwargs</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">current_app</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span> |
: | : | ||
− | <code>viewname</code> | + | <code>viewname</code> 可以是 [[../../topics/http/urls#naming-url-patterns|URL 模式名称]] 或可调用的视图对象。 例如,给定以下 <code>url</code>: |
<div class="highlight-default notranslate"> | <div class="highlight-default notranslate"> | ||
第19行: | 第20行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python">from news import views |
− | path('archive/', views.archive, name='news-archive')</ | + | path('archive/', views.archive, name='news-archive')</syntaxhighlight> |
</div> | </div> | ||
</div> | </div> | ||
− | + | 您可以使用以下任何一种方法来反转 URL: | |
<div class="highlight-default notranslate"> | <div class="highlight-default notranslate"> | ||
第32行: | 第33行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python"># using the named URL |
reverse('news-archive') | reverse('news-archive') | ||
第38行: | 第39行: | ||
# (This is discouraged because you can't reverse namespaced views this way.) | # (This is discouraged because you can't reverse namespaced views this way.) | ||
from news import views | from news import views | ||
− | reverse(views.archive)</ | + | reverse(views.archive)</syntaxhighlight> |
</div> | </div> | ||
</div> | </div> | ||
− | + | 如果 URL 接受参数,您可以在 <code>args</code> 中传递它们。 例如: | |
<div class="highlight-default notranslate"> | <div class="highlight-default notranslate"> | ||
第49行: | 第50行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python">from django.urls import reverse |
def myview(request): | def myview(request): | ||
− | return HttpResponseRedirect(reverse('arch-summary', args=[1945]))</ | + | return HttpResponseRedirect(reverse('arch-summary', args=[1945]))</syntaxhighlight> |
</div> | </div> | ||
</div> | </div> | ||
− | + | 您也可以通过 <code>kwargs</code> 而不是 <code>args</code>。 例如: | |
<div class="highlight-default notranslate"> | <div class="highlight-default notranslate"> | ||
第63行: | 第64行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python">>>> reverse('admin:app_list', kwargs={'app_label': 'auth'}) |
− | '/admin/auth/'</ | + | '/admin/auth/'</syntaxhighlight> |
</div> | </div> | ||
</div> | </div> | ||
− | <code>args</code> | + | <code>args</code>和<code>kwargs</code>不能同时传给<code>reverse()</code>。 |
− | + | 如果无法进行匹配,<code>reverse()</code> 会引发 [[../exceptions#django.urls|NoReverseMatch]] 异常。 | |
− | [[../exceptions#django.urls| | ||
− | + | <code>reverse()</code> 函数可以反转 URL 的多种正则表达式模式,但不是所有可能的模式。 目前的主要限制是模式不能包含使用竖线 (<code>"|"</code>) 字符的替代选择。 你可以很高兴地使用这样的模式来匹配传入的 URL 并将它们发送到视图,但你不能逆转这样的模式。 | |
− | |||
− | |||
− | |||
− | |||
− | |||
− | + | <code>current_app</code> 参数允许您向解析器提供提示,指示当前正在执行的视图所属的应用程序。 根据 [[../../topics/http/urls#topics-http-reversing-url-namespaces|命名空间 URL 解析策略]] ,此 <code>current_app</code> 参数用作将应用程序命名空间解析为特定应用程序实例上的 URL 的提示。 | |
− | |||
− | |||
− | |||
− | [[../../topics/http/urls#topics-http-reversing-url-namespaces|< | ||
− | + | <code>urlconf</code> 参数是 URLconf 模块,包含用于反向的 URL 模式。 默认情况下,使用当前线程的根 URLconf。 | |
− | |||
<div class="admonition note"> | <div class="admonition note"> | ||
− | + | 笔记 | |
− | + | <code>reverse()</code> 返回的字符串已经是 [[../unicode#uri-and-iri-handling|urlquoted]]。 例如: | |
− | [[../unicode#uri-and-iri-handling| | ||
<div class="highlight-default notranslate"> | <div class="highlight-default notranslate"> | ||
第101行: | 第90行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python">>>> reverse('cities', args=['Orléans']) |
− | '.../Orl%C3%A9ans/'</ | + | '.../Orl%C3%A9ans/'</syntaxhighlight> |
</div> | </div> | ||
</div> | </div> | ||
− | + | 对 <code>reverse()</code> 的输出应用进一步编码(例如 <code>urllib.parse.quote()</code>)可能会产生不良结果。 | |
− | |||
第116行: | 第104行: | ||
<div id="reverse-lazy" class="section"> | <div id="reverse-lazy" class="section"> | ||
− | == | + | == reverse_lazy() == |
− | + | [[#reverse|reverse()]] 的懒惰评估版本。 | |
− | ; < | + | ; <span class="sig-name descname"><span class="pre">reverse_lazy</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">viewname</span></span>'', ''<span class="n"><span class="pre">urlconf</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">args</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">kwargs</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">current_app</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span> |
: | : | ||
− | + | 当您需要在加载项目的 URLConf 之前使用 URL 反转时,它很有用。 需要此功能的一些常见情况是: | |
− | |||
− | * | + | * 提供反向 URL 作为通用基于类的视图的 <code>url</code> 属性。 |
− | * | + | * 向装饰器提供反向 URL(例如 [[../../topics/auth/default#django.contrib.auth.decorators|django.contrib.auth.decorators.permission_required()]] 装饰器的 <code>login_url</code> 参数)。 |
− | * | + | * 提供反向 URL 作为函数签名中参数的默认值。 |
第134行: | 第121行: | ||
<div id="resolve" class="section"> | <div id="resolve" class="section"> | ||
− | == | + | == resolve() == |
− | + | <code>resolve()</code> 函数可用于解析 URL 路径到相应的视图函数。 它具有以下签名: | |
− | |||
− | ; < | + | ; <span class="sig-name descname"><span class="pre">resolve</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">path</span></span>'', ''<span class="n"><span class="pre">urlconf</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span> |
: | : | ||
− | <code>path</code> | + | <code>path</code> 是你要解析的 URL 路径。 与 [[#django.urls.reverse|reverse()]] 一样,您无需担心 <code>urlconf</code> 参数。 该函数返回一个 [[#django.urls.ResolverMatch|ResolverMatch]] 对象,该对象允许您访问有关已解析 URL 的各种元数据。 |
− | [[#django.urls.reverse| | ||
− | |||
− | |||
− | + | 如果 URL 未解析,该函数会引发 [[../exceptions#django.urls|Resolver404]] 异常([[../../topics/http/views#django.http|Http404]] 的子类)。 | |
− | [[../exceptions#django.urls| | ||
− | [[../../topics/http/views#django.http| | ||
<dl> | <dl> | ||
− | <dt>''class'' < | + | <dt>''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">ResolverMatch</span></span></dt> |
<dd><dl> | <dd><dl> | ||
− | <dt>< | + | <dt><span class="sig-name descname"><span class="pre">func</span></span></dt> |
− | <dd><p> | + | <dd><p>将用于提供 URL 的视图函数</p></dd></dl> |
<dl> | <dl> | ||
− | <dt>< | + | <dt><span class="sig-name descname"><span class="pre">args</span></span></dt> |
− | <dd><p> | + | <dd><p>从 URL 解析的将传递给视图函数的参数。</p></dd></dl> |
− | |||
<dl> | <dl> | ||
− | <dt>< | + | <dt><span class="sig-name descname"><span class="pre">kwargs</span></span></dt> |
− | <dd><p> | + | <dd><p>从 URL 解析的将传递给视图函数的关键字参数。</p></dd></dl> |
− | |||
<dl> | <dl> | ||
− | <dt>< | + | <dt><span class="sig-name descname"><span class="pre">url_name</span></span></dt> |
− | <dd><p> | + | <dd><p>与 URL 匹配的 URL 模式的名称。</p></dd></dl> |
<dl> | <dl> | ||
− | <dt>< | + | <dt><span class="sig-name descname"><span class="pre">route</span></span></dt> |
<dd><div class="versionadded"> | <dd><div class="versionadded"> | ||
− | + | <p><span class="versionmodified added">2.2 版中的新功能。</span></p> | |
</div> | </div> | ||
− | <p> | + | <p>匹配 URL 模式的路由。</p> |
− | <p> | + | <p>例如,如果 <code>path('users/<id>/', ...)</code> 是匹配模式,则 <code>route</code> 将包含 <code>'users/<id>/'</code>。</p></dd></dl> |
− | <code>route</code> | ||
<dl> | <dl> | ||
− | <dt>< | + | <dt><span class="sig-name descname"><span class="pre">app_name</span></span></dt> |
− | <dd><p> | + | <dd><p>与 URL 匹配的 URL 模式的应用程序命名空间。</p></dd></dl> |
− | URL | ||
<dl> | <dl> | ||
− | <dt>< | + | <dt><span class="sig-name descname"><span class="pre">app_names</span></span></dt> |
− | <dd><p> | + | <dd><p>与 URL 匹配的 URL 模式的完整应用程序命名空间中各个命名空间组件的列表。 例如,如果 <code>app_name</code> 是 <code>'foo:bar'</code>,那么 <code>app_names</code> 将是 <code>['foo', 'bar']</code>。</p></dd></dl> |
− | |||
− | |||
− | |||
<dl> | <dl> | ||
− | <dt>< | + | <dt><span class="sig-name descname"><span class="pre">namespace</span></span></dt> |
− | <dd><p> | + | <dd><p>与 URL 匹配的 URL 模式的实例命名空间。</p></dd></dl> |
− | URL | ||
<dl> | <dl> | ||
− | <dt>< | + | <dt><span class="sig-name descname"><span class="pre">namespaces</span></span></dt> |
− | <dd><p> | + | <dd><p>与 URL 匹配的 URL 模式的完整实例命名空间中各个命名空间组件的列表。 即,如果命名空间是 <code>foo:bar</code>,那么命名空间将是 <code>['foo', 'bar']</code>。</p></dd></dl> |
− | |||
− | |||
− | <code>['foo', 'bar']</code> | ||
<dl> | <dl> | ||
− | <dt>< | + | <dt><span class="sig-name descname"><span class="pre">view_name</span></span></dt> |
− | <dd><p> | + | <dd><p>与 URL 匹配的视图的名称,包括命名空间(如果有)。</p></dd></dl> |
− | |||
</dd></dl> | </dd></dl> | ||
− | + | 然后可以查询 [[#django.urls.ResolverMatch|ResolverMatch]] 对象以提供有关与 URL 匹配的 URL 模式的信息: | |
− | |||
<div class="highlight-default notranslate"> | <div class="highlight-default notranslate"> | ||
第219行: | 第187行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python"># Resolve a URL |
match = resolve('/some/path/') | match = resolve('/some/path/') | ||
# Print the URL pattern that matches the URL | # Print the URL pattern that matches the URL | ||
− | print(match.url_name)</ | + | print(match.url_name)</syntaxhighlight> |
</div> | </div> | ||
</div> | </div> | ||
− | + | [[#django.urls.ResolverMatch|ResolverMatch]] 对象也可以分配给三元组: | |
<div class="highlight-default notranslate"> | <div class="highlight-default notranslate"> | ||
第233行: | 第201行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python">func, args, kwargs = resolve('/some/path/')</syntaxhighlight> |
</div> | </div> | ||
</div> | </div> | ||
− | + | [[#django.urls.resolve|resolve()]] 的一种可能用途是在重定向到视图之前测试视图是否会引发 <code>Http404</code> 错误: | |
− | |||
<div class="highlight-default notranslate"> | <div class="highlight-default notranslate"> | ||
第245行: | 第212行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python">from urllib.parse import urlparse |
from django.urls import resolve | from django.urls import resolve | ||
from django.http import Http404, HttpResponseRedirect | from django.http import Http404, HttpResponseRedirect | ||
第262行: | 第229行: | ||
except Http404: | except Http404: | ||
return HttpResponseRedirect('/') | return HttpResponseRedirect('/') | ||
− | return response</ | + | return response</syntaxhighlight> |
</div> | </div> | ||
第271行: | 第238行: | ||
<div id="get-script-prefix" class="section"> | <div id="get-script-prefix" class="section"> | ||
− | == | + | == get_script_prefix() == |
− | ; < | + | ; <span class="sig-name descname"><span class="pre">get_script_prefix</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span> |
: | : | ||
− | + | 通常,您应该始终使用 [[#django.urls.reverse|reverse()]] 来定义应用程序中的 URL。 但是,如果您的应用程序构建了 URL 层次结构本身的一部分,您可能偶尔需要生成 URL。 在这种情况下,您需要能够在其 Web 服务器中找到 Django 项目的基本 URL(通常,[[#django.urls.reverse|reverse()]] 会为您处理此问题)。 在这种情况下,您可以调用 <code>get_script_prefix()</code>,这将返回 Django 项目 URL 的脚本前缀部分。 如果您的 Django 项目位于其 Web 服务器的根目录,则始终为 <code>"/"</code>。 | |
− | |||
− | URL | ||
− | |||
− | |||
− | |||
− | |||
− | |||
</div> | </div> | ||
+ | |||
+ | </div> | ||
+ | <div class="clearer"> | ||
+ | |||
+ | |||
</div> | </div> | ||
− | [[Category:Django 3.0.x | + | [[Category:Django 3.0.x 文档]] |
2021年10月31日 (日) 04:10的最新版本
django.urls 实用功能
reverse()
如果你需要在你的代码中使用类似于 :ttag:`url` 模板标签的东西,Django 提供了以下功能:
- reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None)
viewname
可以是 URL 模式名称 或可调用的视图对象。 例如,给定以下 url
:
您可以使用以下任何一种方法来反转 URL:
如果 URL 接受参数,您可以在 args
中传递它们。 例如:
您也可以通过 kwargs
而不是 args
。 例如:
args
和kwargs
不能同时传给reverse()
。
如果无法进行匹配,reverse()
会引发 NoReverseMatch 异常。
reverse()
函数可以反转 URL 的多种正则表达式模式,但不是所有可能的模式。 目前的主要限制是模式不能包含使用竖线 ("|"
) 字符的替代选择。 你可以很高兴地使用这样的模式来匹配传入的 URL 并将它们发送到视图,但你不能逆转这样的模式。
current_app
参数允许您向解析器提供提示,指示当前正在执行的视图所属的应用程序。 根据 命名空间 URL 解析策略 ,此 current_app
参数用作将应用程序命名空间解析为特定应用程序实例上的 URL 的提示。
urlconf
参数是 URLconf 模块,包含用于反向的 URL 模式。 默认情况下,使用当前线程的根 URLconf。
reverse_lazy()
reverse() 的懒惰评估版本。
- reverse_lazy(viewname, urlconf=None, args=None, kwargs=None, current_app=None)
当您需要在加载项目的 URLConf 之前使用 URL 反转时,它很有用。 需要此功能的一些常见情况是:
- 提供反向 URL 作为通用基于类的视图的
url
属性。 - 向装饰器提供反向 URL(例如 django.contrib.auth.decorators.permission_required() 装饰器的
login_url
参数)。 - 提供反向 URL 作为函数签名中参数的默认值。
resolve()
resolve()
函数可用于解析 URL 路径到相应的视图函数。 它具有以下签名:
- resolve(path, urlconf=None)
path
是你要解析的 URL 路径。 与 reverse() 一样,您无需担心 urlconf
参数。 该函数返回一个 ResolverMatch 对象,该对象允许您访问有关已解析 URL 的各种元数据。
如果 URL 未解析,该函数会引发 Resolver404 异常(Http404 的子类)。
- class ResolverMatch
- func
将用于提供 URL 的视图函数
- args
从 URL 解析的将传递给视图函数的参数。
- kwargs
从 URL 解析的将传递给视图函数的关键字参数。
- url_name
与 URL 匹配的 URL 模式的名称。
- route
2.2 版中的新功能。
匹配 URL 模式的路由。
例如,如果
path('users/<id>/', ...)
是匹配模式,则route
将包含'users/<id>/'
。
- app_name
与 URL 匹配的 URL 模式的应用程序命名空间。
- app_names
与 URL 匹配的 URL 模式的完整应用程序命名空间中各个命名空间组件的列表。 例如,如果
app_name
是'foo:bar'
,那么app_names
将是['foo', 'bar']
。
- namespace
与 URL 匹配的 URL 模式的实例命名空间。
- namespaces
与 URL 匹配的 URL 模式的完整实例命名空间中各个命名空间组件的列表。 即,如果命名空间是
foo:bar
,那么命名空间将是['foo', 'bar']
。
- view_name
与 URL 匹配的视图的名称,包括命名空间(如果有)。
然后可以查询 ResolverMatch 对象以提供有关与 URL 匹配的 URL 模式的信息:
ResolverMatch 对象也可以分配给三元组:
resolve() 的一种可能用途是在重定向到视图之前测试视图是否会引发 Http404
错误: