[英]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.