了解 django.shortcuts.redirect [英] Understanding django.shortcuts.redirect
问题描述
我在理解 redirect
或更确切地说 reverse
的实际工作原理时遇到了一些问题.
I have a couple problems understanding how redirect
or rather reverse
really work.
在主 urls.py 我有:
In the main urls.py I have:
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
所以我做到了:
When you call /monitor
I want to redirect it to /monitor/abc
so I did:
def index(request):
return redirect("abc")
def abc(render, id=None):
return render_to_response("monitor/list.htmld", {})
但是我遇到了 NoReverseMatch
异常.但是当我这样做时:
But I got an NoReverseMatch
exception. But when I do:
def index(request):
return redirect("abc/")
然后它突然起作用了.
我无法完全理解为什么.为什么 reverse
使用 abc
失败,但使用 abc/
失败?reverse
如何知道重定向也应该包含 monitor/
?如果我在主 urls.py 中有另一个名为 xyz
的应用程序,它也有一个 abc
视图怎么办?
I cannot fully understand why. Why did reverse
fail with abc
but not with abc/
? And how does reverse
know that the redirect should include monitor/
as well? What if I had in the main urls.py another app called xyz
which also has a abc
view?
推荐答案
为什么使用abc"反向失败而不使用abc/"?
Why did reverse fail with 'abc' but not with 'abc/'?
因为它将它解释为视图名称(并且您确实有一个名为 'abc'
的视图,请参阅您的 monitor.urls
文件).这意味着 Django 将调用 reverse
来计算 URL.值 abc/
被解释为一个实际的 URL,这意味着 Django 不会调用 reverse
来确定 URL.
Because it interpreted it as a view name (and you indeed have a view named 'abc'
, see your monitor.urls
file). This means Django will call reverse
to compute the URL. The value abc/
is interpreted as an actual URL which means Django won't call reverse
to determine the URL.
这也解释了为什么 reverse
失败:名称为 abc
的视图也需要一个名为 id
的参数.否则 Django 将无法查找 URL,因为没有不带参数的 abc
视图.
This also explains why reverse
failed: the view with name abc
also requires an argument called id
. Otherwise Django won't be able to lookup the URL as there is no view called abc
without parameters.
基于文档,您应该能够使用以下方法反转 URL:
Based on the documentation you should be able to reverse the URL using:
redirect("abc", id=...)
其中 ...
是 id
参数的值.
where ...
is the value of the id
parameter.
反向如何知道重定向应该包括监视器/?
And how does reverse know that the redirect should include monitor/ as well?
那是因为它知道哪些 URL 可用并且 1) 它知道名为 abc
的视图的定义位置和 2) 它知道 monitors.urls
包含在monitor/
在前面.
That is because it knows what URLs are available and 1) it knows where the view called abc
is defined and 2) it knows that monitors.urls
is included with monitor/
in front.
如果我在主 urls.py 中有另一个名为xyz"的应用程序,它也有一个abc"视图怎么办?
What if I had in the main urls.py another app called "xyz" which also has a "abc" view?
在这种情况下,您必须使用 命名空间.
In that case you have to use namespaces.
这篇关于了解 django.shortcuts.redirect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!