Skip to main content
 首页 » 编程设计

python之了解 django.shortcuts.redirect

2024年08月30日27myhome

我在理解 redirect 或者更确切地说 reverse 是如何工作时遇到一些问题。

在主要的 urls.py 中我有:

from django.conf.urls import patterns, include, url 
from django.views.generic.simple import redirect_to 
 
urlpatterns = patterns('', 
        url(r'^$', redirect_to, {'url': '/monitor/'}), 
        url(r'^monitor/', include('monitor.urls')), 
) 

在 monitors.urls 中我有:

from django.conf.urls import patterns, include, url  
 
urlpatterns = patterns('monitor.views', 
        (r'^$', 'index'), 
        (r'^abc/(?P<id>.*$)', 'abc'), 
)    

当你调用 /monitor 时,我想将它重定向到 /monitor/abc 所以我做了:

def index(request): 
    return redirect("abc") 
 
def abc(render, id=None): 
    return render_to_response("monitor/list.htmld", {}) 

但是我遇到了一个NoReverseMatch 异常。但是当我这样做时:

def index(request): 
    return redirect("abc/") 

然后它突然起作用了。

我无法完全理解为什么。为什么 reverse 使用 abc 而不是使用 abc/ 失败? reverse 如何知道重定向也应该包含 monitor/?如果我在主 urls.py 中有另一个名为 xyz 的应用程序,它也有一个 abc View 怎么办?

请您参考如下方法:

Why did reverse fail with 'abc' but not with 'abc/'?

因为它将它解释为一个 View 名称(并且您确实有一个名为 'abc' 的 View ,请参阅您的 monitor.urls 文件)。这意味着 Django 将调用 reverse 来计算 URL。值 abc/ 被解释为实际 URL,这意味着 Django 不会调用 reverse 来确定 URL。

这也解释了为什么 reverse 失败:名称为 abc 的 View 还需要一个名为 id 的参数。否则 Django 将无法查找 URL,因为没有不带参数的名为 abc 的 View 。

基于 the documentation您应该能够使用以下方法反转 URL:

redirect("abc", id=...) 

其中 ... 是 id 参数的值。

And how does reverse know that the redirect should include monitor/ as well?

那是因为它知道哪些 URL 可用,并且 1) 它知道名为 abc 的 View 在何处定义,以及 2) 它知道 monitors.urls 包含在monitor/在前面。

What if I had in the main urls.py another app called "xyz" which also has a "abc" view?

在这种情况下,您必须使用 namespaces .