“Django/docs/3.0.x/ref/urlresolvers”的版本间差异

来自菜鸟教程
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>
= <code>django.urls</code> utility functions =
+
= django.urls 实用功能 =
  
 
<div id="reverse" class="section">
 
<div id="reverse" class="section">
第8行: 第9行:
 
== reverse() ==
 
== reverse() ==
  
如果在你的代码中,需要使用一些类似url模板标签,Django提供了下列功能:
+
如果你需要在你的代码中使用类似于 [[#id1|:ttag:`url`]] 模板标签的东西,Django 提供了以下功能:
  
; <code>reverse</code><span class="sig-paren">(</span>''<span class="n">viewname</span>'', ''<span class="n">urlconf</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">args</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">kwargs</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">current_app</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span>
+
; <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> 可以是一个url模式名称或一个可调用的视图对象。例如,给定以下 <code>url</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">
  
<pre>from news import views
+
<syntaxhighlight lang="python">from news import views
  
path('archive/', views.archive, name='news-archive')</pre>
+
path('archive/', views.archive, name='news-archive')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
you can use any of the following to reverse the URL:
+
您可以使用以下任何一种方法来反转 URL:
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第32行: 第33行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre># using the named URL
+
<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)</pre>
+
reverse(views.archive)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
If the URL accepts arguments, you may pass them in <code>args</code>. For example:
+
如果 URL 接受参数,您可以在 <code>args</code> 中传递它们。 例如:
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第49行: 第50行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from django.urls import reverse
+
<syntaxhighlight lang="python">from django.urls import reverse
  
 
def myview(request):
 
def myview(request):
     return HttpResponseRedirect(reverse('arch-summary', args=[1945]))</pre>
+
     return HttpResponseRedirect(reverse('arch-summary', args=[1945]))</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
You can also pass <code>kwargs</code> instead of <code>args</code>. For example:
+
您也可以通过 <code>kwargs</code> 而不是 <code>args</code>。 例如:
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第63行: 第64行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; reverse('admin:app_list', kwargs={'app_label': 'auth'})
+
<syntaxhighlight lang="python">>>> reverse('admin:app_list', kwargs={'app_label': 'auth'})
'/admin/auth/'</pre>
+
'/admin/auth/'</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<code>args</code> and <code>kwargs</code> cannot be passed to <code>reverse()</code> at the same time.
+
<code>args</code><code>kwargs</code>不能同时传给<code>reverse()</code>
  
If no match can be made, <code>reverse()</code> raises a
+
如果无法进行匹配,<code>reverse()</code> 会引发 [[../exceptions#django.urls|NoReverseMatch]] 异常。
[[../exceptions#django.urls|<code>NoReverseMatch</code>]] exception.
 
  
The <code>reverse()</code> function can reverse a large variety of regular expression
+
<code>reverse()</code> 函数可以反转 URL 的多种正则表达式模式,但不是所有可能的模式。 目前的主要限制是模式不能包含使用竖线 (<code>&quot;|&quot;</code>) 字符的替代选择。 你可以很高兴地使用这样的模式来匹配传入的 URL 并将它们发送到视图,但你不能逆转这样的模式。
patterns for URLs, but not every possible one. The main restriction at the
 
moment is that the pattern cannot contain alternative choices using the
 
vertical bar (<code>&quot;|&quot;</code>) character. You can quite happily use such patterns for
 
matching against incoming URLs and sending them off to views, but you cannot
 
reverse such patterns.
 
  
The <code>current_app</code> argument allows you to provide a hint to the resolver
+
<code>current_app</code> 参数允许您向解析器提供提示,指示当前正在执行的视图所属的应用程序。 根据 [[../../topics/http/urls#topics-http-reversing-url-namespaces|命名空间 URL 解析策略]] ,此 <code>current_app</code> 参数用作将应用程序命名空间解析为特定应用程序实例上的 URL 的提示。
indicating the application to which the currently executing view belongs.
 
This <code>current_app</code> argument is used as a hint to resolve application
 
namespaces into URLs on specific application instances, according to the
 
[[../../topics/http/urls#topics-http-reversing-url-namespaces|<span class="std std-ref">namespaced URL resolution strategy</span>]].
 
  
The <code>urlconf</code> argument is the URLconf module containing the URL patterns to
+
<code>urlconf</code> 参数是 URLconf 模块,包含用于反向的 URL 模式。 默认情况下,使用当前线程的根 URLconf。
use for reversing. By default, the root URLconf for the current thread is used.
 
  
 
<div class="admonition note">
 
<div class="admonition note">
  
注解
+
笔记
  
The string returned by <code>reverse()</code> is already
+
<code>reverse()</code> 返回的字符串已经是 [[../unicode#uri-and-iri-handling|urlquoted]]。 例如:
[[../unicode#uri-and-iri-handling|<span class="std std-ref">urlquoted</span>]]. For example:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第101行: 第90行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; reverse('cities', args=['Orléans'])
+
<syntaxhighlight lang="python">>>> reverse('cities', args=['Orléans'])
'.../Orl%C3%A9ans/'</pre>
+
'.../Orl%C3%A9ans/'</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Applying further encoding (such as <code>urllib.parse.quote()</code>) to the output
+
<code>reverse()</code> 的输出应用进一步编码(例如 <code>urllib.parse.quote()</code>)可能会产生不良结果。
of <code>reverse()</code> may produce undesirable results.
 
  
  
第116行: 第104行:
 
<div id="reverse-lazy" class="section">
 
<div id="reverse-lazy" class="section">
  
== <code>reverse_lazy()</code> ==
+
== reverse_lazy() ==
  
A lazily evaluated version of [[#reverse|reverse()]].
+
[[#reverse|reverse()]] 的懒惰评估版本。
  
; <code>reverse_lazy</code><span class="sig-paren">(</span>''<span class="n">viewname</span>'', ''<span class="n">urlconf</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">args</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">kwargs</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">current_app</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span>
+
; <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>
 
:  
 
:  
  
It is useful for when you need to use a URL reversal before your project's
+
当您需要在加载项目的 URLConf 之前使用 URL 反转时,它很有用。 需要此功能的一些常见情况是:
URLConf is loaded. Some common cases where this function is necessary are:
 
  
* providing a reversed URL as the <code>url</code> attribute of a generic class-based view.
+
* 提供反向 URL 作为通用基于类的视图的 <code>url</code> 属性。
* providing a reversed URL to a decorator (such as the <code>login_url</code> argument for the [[../../topics/auth/default#django.contrib.auth.decorators|<code>django.contrib.auth.decorators.permission_required()</code>]] decorator).
+
* 向装饰器提供反向 URL(例如 [[../../topics/auth/default#django.contrib.auth.decorators|django.contrib.auth.decorators.permission_required()]] 装饰器的 <code>login_url</code> 参数)。
* providing a reversed URL as a default value for a parameter in a function's signature.
+
* 提供反向 URL 作为函数签名中参数的默认值。
  
  
第134行: 第121行:
 
<div id="resolve" class="section">
 
<div id="resolve" class="section">
  
== <code>resolve()</code> ==
+
== resolve() ==
  
The <code>resolve()</code> function can be used for resolving URL paths to the
+
<code>resolve()</code> 函数可用于解析 URL 路径到相应的视图函数。 它具有以下签名:
corresponding view functions. It has the following signature:
 
  
; <code>resolve</code><span class="sig-paren">(</span>''<span class="n">path</span>'', ''<span class="n">urlconf</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span>
+
; <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> is the URL path you want to resolve. As with
+
<code>path</code> 是你要解析的 URL 路径。 与 [[#django.urls.reverse|reverse()]] 一样,您无需担心 <code>urlconf</code> 参数。 该函数返回一个 [[#django.urls.ResolverMatch|ResolverMatch]] 对象,该对象允许您访问有关已解析 URL 的各种元数据。
[[#django.urls.reverse|<code>reverse()</code>]], you don't need to worry about the <code>urlconf</code>
 
parameter. The function returns a [[#django.urls.ResolverMatch|<code>ResolverMatch</code>]] object that allows you
 
to access various metadata about the resolved URL.
 
  
If the URL does not resolve, the function raises a
+
如果 URL 未解析,该函数会引发 [[../exceptions#django.urls|Resolver404]] 异常([[../../topics/http/views#django.http|Http404]] 的子类)。
[[../exceptions#django.urls|<code>Resolver404</code>]] exception (a subclass of
 
[[../../topics/http/views#django.http|<code>Http404</code>]]) .
 
  
 
<dl>
 
<dl>
<dt>''class'' <code>ResolverMatch</code></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">ResolverMatch</span></span></dt>
 
<dd><dl>
 
<dd><dl>
<dt><code>func</code></dt>
+
<dt><span class="sig-name descname"><span class="pre">func</span></span></dt>
<dd><p>The view function that would be used to serve the URL</p></dd></dl>
+
<dd><p>将用于提供 URL 的视图函数</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>args</code></dt>
+
<dt><span class="sig-name descname"><span class="pre">args</span></span></dt>
<dd><p>The arguments that would be passed to the view function, as
+
<dd><p>URL 解析的将传递给视图函数的参数。</p></dd></dl>
parsed from the URL.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>kwargs</code></dt>
+
<dt><span class="sig-name descname"><span class="pre">kwargs</span></span></dt>
<dd><p>The keyword arguments that would be passed to the view
+
<dd><p>URL 解析的将传递给视图函数的关键字参数。</p></dd></dl>
function, as parsed from the URL.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>url_name</code></dt>
+
<dt><span class="sig-name descname"><span class="pre">url_name</span></span></dt>
<dd><p>The name of the URL pattern that matches the URL.</p></dd></dl>
+
<dd><p>URL 匹配的 URL 模式的名称。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>route</code></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>The route of the matching URL pattern.</p>
+
<p>匹配 URL 模式的路由。</p>
<p>For example, if <code>path('users/&lt;id&gt;/', ...)</code> is the matching pattern,
+
<p>例如,如果 <code>path('users/&lt;id&gt;/', ...)</code> 是匹配模式,则 <code>route</code> 将包含 <code>'users/&lt;id&gt;/'</code></p></dd></dl>
<code>route</code> will contain <code>'users/&lt;id&gt;/'</code>.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>app_name</code></dt>
+
<dt><span class="sig-name descname"><span class="pre">app_name</span></span></dt>
<dd><p>The application namespace for the URL pattern that matches the
+
<dd><p>URL 匹配的 URL 模式的应用程序命名空间。</p></dd></dl>
URL.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>app_names</code></dt>
+
<dt><span class="sig-name descname"><span class="pre">app_names</span></span></dt>
<dd><p>The list of individual namespace components in the full
+
<dd><p>URL 匹配的 URL 模式的完整应用程序命名空间中各个命名空间组件的列表。 例如,如果 <code>app_name</code> <code>'foo:bar'</code>,那么 <code>app_names</code> 将是 <code>['foo', 'bar']</code></p></dd></dl>
application namespace for the URL pattern that matches the URL.
 
For example, if the <code>app_name</code> is <code>'foo:bar'</code>, then <code>app_names</code>
 
will be <code>['foo', 'bar']</code>.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>namespace</code></dt>
+
<dt><span class="sig-name descname"><span class="pre">namespace</span></span></dt>
<dd><p>The instance namespace for the URL pattern that matches the
+
<dd><p>URL 匹配的 URL 模式的实例命名空间。</p></dd></dl>
URL.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>namespaces</code></dt>
+
<dt><span class="sig-name descname"><span class="pre">namespaces</span></span></dt>
<dd><p>The list of individual namespace components in the full
+
<dd><p>URL 匹配的 URL 模式的完整实例命名空间中各个命名空间组件的列表。 即,如果命名空间是 <code>foo:bar</code>,那么命名空间将是 <code>['foo', 'bar']</code></p></dd></dl>
instance namespace for the URL pattern that matches the URL.
 
i.e., if the namespace is <code>foo:bar</code>, then namespaces will be
 
<code>['foo', 'bar']</code>.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>view_name</code></dt>
+
<dt><span class="sig-name descname"><span class="pre">view_name</span></span></dt>
<dd><p>The name of the view that matches the URL, including the namespace if
+
<dd><p>URL 匹配的视图的名称,包括命名空间(如果有)。</p></dd></dl>
there is one.</p></dd></dl>
 
 
</dd></dl>
 
</dd></dl>
  
A [[#django.urls.ResolverMatch|<code>ResolverMatch</code>]] object can then be interrogated to provide
+
然后可以查询 [[#django.urls.ResolverMatch|ResolverMatch]] 对象以提供有关与 URL 匹配的 URL 模式的信息:
information about the URL pattern that matches a URL:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第219行: 第187行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre># Resolve a URL
+
<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)</pre>
+
print(match.url_name)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
A [[#django.urls.ResolverMatch|<code>ResolverMatch</code>]] object can also be assigned to a triple:
+
[[#django.urls.ResolverMatch|ResolverMatch]] 对象也可以分配给三元组:
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第233行: 第201行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>func, args, kwargs = resolve('/some/path/')</pre>
+
<syntaxhighlight lang="python">func, args, kwargs = resolve('/some/path/')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
One possible use of [[#django.urls.resolve|<code>resolve()</code>]] would be to test whether a
+
[[#django.urls.resolve|resolve()]] 的一种可能用途是在重定向到视图之前测试视图是否会引发 <code>Http404</code> 错误:
view would raise a <code>Http404</code> error before redirecting to it:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第245行: 第212行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from urllib.parse import urlparse
+
<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</pre>
+
     return response</syntaxhighlight>
  
 
</div>
 
</div>
第271行: 第238行:
 
<div id="get-script-prefix" class="section">
 
<div id="get-script-prefix" class="section">
  
== <code>get_script_prefix()</code> ==
+
== get_script_prefix() ==
  
; <code>get_script_prefix</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-name descname"><span class="pre">get_script_prefix</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
 
:  
 
:  
  
Normally, you should always use [[#django.urls.reverse|<code>reverse()</code>]] to define URLs
+
通常,您应该始终使用 [[#django.urls.reverse|reverse()]] 来定义应用程序中的 URL。 但是,如果您的应用程序构建了 URL 层次结构本身的一部分,您可能偶尔需要生成 URL。 在这种情况下,您需要能够在其 Web 服务器中找到 Django 项目的基本 URL(通常,[[#django.urls.reverse|reverse()]] 会为您处理此问题)。 在这种情况下,您可以调用 <code>get_script_prefix()</code>,这将返回 Django 项目 URL 的脚本前缀部分。 如果您的 Django 项目位于其 Web 服务器的根目录,则始终为 <code>&quot;/&quot;</code>
within your application. However, if your application constructs part of the
 
URL hierarchy itself, you may occasionally need to generate URLs. In that
 
case, you need to be able to find the base URL of the Django project within
 
its Web server (normally, [[#django.urls.reverse|<code>reverse()</code>]] takes care of this for
 
you). In that case, you can call <code>get_script_prefix()</code>, which will return
 
the script prefix portion of the URL for your Django project. If your Django
 
project is at the root of its web server, this is always <code>&quot;/&quot;</code>.
 
  
  
 
</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

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。 例如:

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

argskwargs不能同时传给reverse()

如果无法进行匹配,reverse() 会引发 NoReverseMatch 异常。

reverse() 函数可以反转 URL 的多种正则表达式模式,但不是所有可能的模式。 目前的主要限制是模式不能包含使用竖线 ("|") 字符的替代选择。 你可以很高兴地使用这样的模式来匹配传入的 URL 并将它们发送到视图,但你不能逆转这样的模式。

current_app 参数允许您向解析器提供提示,指示当前正在执行的视图所属的应用程序。 根据 命名空间 URL 解析策略 ,此 current_app 参数用作将应用程序命名空间解析为特定应用程序实例上的 URL 的提示。

urlconf 参数是 URLconf 模块,包含用于反向的 URL 模式。 默认情况下,使用当前线程的根 URLconf。

笔记

reverse() 返回的字符串已经是 urlquoted。 例如:

>>> reverse('cities', args=['Orléans'])
'.../Orl%C3%A9ans/'

reverse() 的输出应用进一步编码(例如 urllib.parse.quote())可能会产生不良结果。


reverse_lazy()

reverse() 的懒惰评估版本。

reverse_lazy(viewname, urlconf=None, args=None, kwargs=None, current_app=None)

当您需要在加载项目的 URLConf 之前使用 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 模式的信息:

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

ResolverMatch 对象也可以分配给三元组:

func, args, kwargs = resolve('/some/path/')

resolve() 的一种可能用途是在重定向到视图之前测试视图是否会引发 Http404 错误:

from urllib.parse import urlparse
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(urlparse(next)[2])
    kwargs['request'] = request
    try:
        view(*args, **kwargs)
    except Http404:
        return HttpResponseRedirect('/')
    return response

get_script_prefix()

get_script_prefix()

通常,您应该始终使用 reverse() 来定义应用程序中的 URL。 但是,如果您的应用程序构建了 URL 层次结构本身的一部分,您可能偶尔需要生成 URL。 在这种情况下,您需要能够在其 Web 服务器中找到 Django 项目的基本 URL(通常,reverse() 会为您处理此问题)。 在这种情况下,您可以调用 get_script_prefix(),这将返回 Django 项目 URL 的脚本前缀部分。 如果您的 Django 项目位于其 Web 服务器的根目录,则始终为 "/"