2012-10-02 21 views
11

我一直在试图找出如何来定义一个Django URLconf中嵌套URL命名空间(这look:like:this)。定义嵌套的命名空间中的URL配置,倒车Django的网址 - 没有任何人有一个有说服力的例子吗?

在此之前,我想通了如何做一个基本的URL命名空间,并与this simple example snippet上来,包含你可以考虑加入一个urls.py文件:

from django.conf.urls import patterns, include, url 

# you can only define a namespace for urls when calling include(): 

app_patterns = patterns('', 
    url(r'^(?P<pk>[\w\-]+)/$', 'yourapp.views.your_view_function', 
     name="your-view"), 
) 

urlpatterns = patterns('', 
    url(r'^view-function/', include(app_patterns, 
     namespace='yournamespace', app_name='yourapp')), 
) 

""" 

    You can now use the namespace when you refer to the view, e.g. a call 
    to `reverse()`: 

    # yourapp/models.py 

    from django.core.urlresolvers import reverse 

    # ... 

    class MyModel(models.Model): 

     def get_absolute_url(self): 
     return reverse('signalqueue:exception-log-entry', kwargs=dict(pk=self.pk)) 

""" 

... W/R/T扣其中the Django documentation在这种情况下根本没有帮助。虽然Django的文档是在所有其他方面太棒了,这是一个例外,有关于嵌套定义URL命名空间的资料就更少。

为了解决这个问题,我想我可能会问,如果有人知道或者知道一个简单明了的和/或自我解释的定义了嵌套命名空间的URLconf例子,他们可以分享。

具体而言,我很好奇前景视图的嵌套部分:需要他们全部被安装Django应用程序?

†)对于好奇,这里有一个(可能有点难以理解)的例子:http://imgur.com/NDn9H。我试图在底部以红色和绿色打印网址,名称为testapp:views:<viewname>,而不是testapp:<viewname>

回答

21

它的工作原理相当直观。 include有一个URLconf的另一个命名空间include将导致嵌套的命名空间。

## urls.py 
nested2 = patterns('', 
    url(r'^index/$', 'index', name='index'), 
) 

nested1 = patterns('', 
    url(r'^nested2/', include(nested2, namespace="nested2"), 
    url(r'^index/$', 'index', name='index'), 
) 

urlpatterns = patterns('', 
    (r'^nested1/', include(nested1, namespace="nested1"), 
) 

reverse('nested1:nested2:index') # should output /nested1/nested2/index/ 
reverse('nested1:index') # should output /nested1/index/ 

这是一个很好的方式来保持网站的组织。我想我可以给出的最好的建议是记住include可以直接使用patterns对象(如我的示例),它允许您使用单个urls.py并将视图拆分为有用的名称空间,而无需创建多个URL文件。

+0

不错,这确实是简单的。谢谢! – fish2000

4

虽然虞姬的答案是正确的,注意django.conf.urls.patterns不再存在(因为Django的1.10)和滑动列表来代替。

同样的例子urls.py现在应该是这样的:

from django.conf.urls import include, url 

nested2 = [ 
    url(r'^index/$', 'index', name='index'), 
] 

nested1 = [ 
    url(r'^nested2/', include(nested2, namespace="nested2"), 
    url(r'^index/$', 'index', name='index'), 
] 

urlpatterns = [ 
    url(r'^nested1/', include(nested1, namespace="nested1"), 
] 

而且仍在使用,如:

reverse('nested1:nested2:index') # should output /nested1/nested2/index/ 
reverse('nested1:index') # should output /nested1/index/ 
+0

不应该'urlpatterns'变量也有'url'函数调用? –

+0

@NathanJones哎呀是的,谢谢 - 纠正。 –