在Understanding django.shortcuts.redirect中,我创建了一个关于reverse和redirect_to的帖子。
当第一个参数是字符串时,我仍然有一些问题要理解reverse是如何工作的。我用reverse阅读了很多次https://docs.djangoproject.com/en/1.4/topics/http/shortcuts/#django.shortcuts.redirect和相应的部分。但是我仍然得到了一个NoReverseMatch异常。
在我的ROOT_URLCONF中
urlpatterns = patterns('',
url(r'^$', redirect_to, {'url': '/monitor/'}),
url(r'^monitor/', include('monitor.urls')),
)在monitor.urls中,我有
urlpatterns = patterns('monitor.views',
(r'^$', 'index'),
(r'^list', 'listall'),
)在monitor.urls中,我已经为index和listall这两个函数定义了代码。在listall中,我添加了以下几行:
def listall(request):
<more code goes here>
print "reversing 1 index: %s " % reverse(index)
print "reversing 2 index: %s " % reverse('index')
render_to_response("monitor/list.htmld", params)如果我访问localhost:3000/monitor/list,那么我可以看到
reversing 1 index: /monitor/ 除此之外,第二个reverse引发了一个异常。为什么?我遗漏了什么?
我追踪到了djangos的代码django.core.urlresolvers.callable和django.core.urlresolvers.get_mod_func。get_mod_func似乎期望出现类似于"a.b“的内容,这就是为什么在callable中,func_name的第一行返回的是"index”,而mod_name的第一行返回的是空字符串。我将我的第二行改为
print "reversing 2 index: %s " % reverse('monitor.views.index')它达到了预期的效果。那么,为什么我需要使用完整的模块和函数名调用reverse (当我使用字符串时),而文档不需要呢?我遗漏了什么?
谢谢
发布于 2012-08-17 01:45:01
我不确定您正在关注文档的哪一部分,但是reverse的第一个参数是访问视图的某种标识方法:它可以是full模式名称、指向视图的完整虚线路径,也可以是视图本身
因此,根据您的示例,第一个方法是out,因为您没有为urlpattern定义名称。第一次尝试时,reverse(index)成功了,因为您确实将视图传递给了它。您的第二次尝试reverse('index')不起作用,因为它需要完整的导入上下文,即'monitor.views.index'。两者之间的区别在于,当它是字符串时,Django必须解释该字符串才能为视图创建导入--而'index‘不足以确定导入路径。
然而,如果你想逆转它们,最好只是命名你的视图,而且你还应该命名你包含的urlpattern,这样两个不同的应用程序就不会冲突。因此,在项目级urls.py中:
urlpatterns = patterns('',
url(r'^$', redirect_to, {'url': '/monitor/'}),
url(r'^monitor/', include('monitor.urls', namespace='monitor', app_name='monitor')),
)然后,在monitor/urls.py中:
urlpatterns = patterns('monitor.views',
(r'^$', 'index', name='index'),
(r'^list', 'listall', name='listall'),
)然后,反转就像reverse('monitor:index')一样简单。
发布于 2012-08-16 19:26:11
您应该这样做:
reverse('monitor:index')在ROOT_URLCONF中,我有
urlpatterns = patterns('',
(r'^$', redirect_to, {'url': '/monitor/'}),
(r'^monitor/', include('monitor.urls'),namespace='monitor'),
)在monitor.url.py中
urlpatterns = patterns('monitor.views',
url(r'^$', 'index',name='index'),
)有关更多详细信息,请查看https://docs.djangoproject.com/en/1.4/topics/http/urls/#django.core.urlresolvers.reverse
https://stackoverflow.com/questions/11985876
复制相似问题