![](/img/trans.png)
[英]django.core.exceptions.ImproperlyConfigured: The included URLconf 'api.urls' does not appear to have any patterns in it
[英]Defining nested namespaces in a URLConf, for reversing Django URLs — does anyone have a cogent example?
我一直试图弄清楚如何在Django URLConf中定义嵌套的URL命名空间( look:like:this
)。
在此之前,我想出了如何做一个基本的URL命名空间,并提出了这个简单的示例代码片段 ,其中包含了您可能放在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 Django文档的推导,在这种情况下,根本没有帮助。 虽然Django的doc在所有其他方面都很棒,但这是规则的一个例外,关于定义嵌套URL命名空间的信息甚至更少。
我想,如果有人拥有或知道一个直接有说服力和/或不言自明的URLconf定义嵌套命名空间的例子,我可能会问他们可以分享这些尝试。
具体来说,我很好奇视图前缀的嵌套部分:需要它们都安装Django应用程序吗?
†)对于好奇,这是一个(可能有点难以理解)的例子: http : //imgur.com/NDn9H 。 我试图将底部以红色和绿色打印的URL命名为testapp:views:<viewname>
而不仅仅是testapp:<viewname>
。
它的工作非常直观。 include
URL配置已经又命名空间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文件。
虽然Yuji的答案是正确的,但请注意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/
。
更新: Django 2.0引入了两个相关的更改。 首先, urls()
函数现在位于django.urls
,因此上面urls.py
示例的第一行将是:
from django.urls import include, url
其次,它引入了path()
函数作为不需要正则表达式的路径的更简单的替代方法。 使用它,示例urls.py
将是这样的:
from django.urls import include, path
nested2 = [
path('index/', 'index', name='index'),
]
nested1 = [
path('nested2/', include(nested2, namespace='nested2'),
path('index/', 'index', name='index'),
]
urlpatterns = [
path('nested1/', include(nested1, namespace='nested1'),
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.