我一直试图弄清楚如何在Django URLConf中定义嵌套的URL命名空间(look:like:this
)。
在此之前,我想出了如何做一个基本的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的doc在所有其他方面都很棒,但这是规则的一个例外,关于定义嵌套URL命名空间的信息甚至更少。
我想,如果有人拥有或知道一个直接有说服力和/或不言自明的URLconf定义嵌套命名空间的例子,我可能会问他们可以分享这些尝试。
具体来说,我很好奇视图前缀的嵌套部分:需要它们都安装Django应用程序吗?
†)对于好奇,这里是一个(可能有点难以理解)的例子:http://imgur.com/NDn9H。我试图将底部以红色和绿色打印的URL命名为testapp:views:<viewname>
,而不仅仅是testapp:<viewname>
。
它的工作非常直观。 qazxsw poi一个urlconf,它有另一个命名空间qazxsw poi将导致嵌套的命名空间。
include
这是保持网址组织的好方法。我想我能给出的最好建议是记住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
并将视图拆分为有用的命名空间,而无需创建多个url文件。
虽然Yuji的答案是正确的,但请注意patterns
不再存在(因为Django 1.10)而使用普通列表。
同样的例子urls.py
现在应该是这样的:
django.conf.urls.patterns
仍然使用像:
urls.py
。
更新:Django 2.0引入了两个相关的更改。首先,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/
,所以上面的urls()
示例的第一行将是:
django.urls
其次,它引入了urls.py
函数作为不需要正则表达式的路径的更简单的替代方法。使用它,示例from django.urls import include, url
将是这样的:
path()