2015-10-13 35 views
0

我在使用reverse()函數和視圖函數作爲參數時遇到問題。當我在默認的urls.py文件中指定URL路由時,它工作正常。但是當我有import到第二個urls.py文件時,我得到了NoReverseMatch-錯誤。反過來查看功能不能與多個urls.py文件一起使用

所以...這就是我的urls.py文件的外觀。

demostore/demostore/urls.py

#demostore/demostore/urls.py 
urlpatterns = [ 
    url(r'^admin/', include(admin.site.urls)), 
    url(r'^', include('lindshop.urls', namespace="shop")), 
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) 

demostore/lindshop/urls.py

#demostore/lindshop/urls.py 
urlpatterns = [ 
    url(r'^$', views.landing, name='index'), 
    ... 
    url(r'^product-index/$', 'lindshop.core.product.views.product_index', name="product_index"), 
] 

product_index觀點是不帶任何參數只是一個空的觀點,看起來像這樣:

def product_index(request): 
    return TemplateResponse(request, "index.html") 

現在...當我打電話

reverse('lindshop.core.product.views.product_index') 

我得到一個NoReverseMatch錯誤。但是,如果我將url(r'^product-index/$'...)放在demostore/demostore.urls.py中,則reverse()可以正常工作。但這不是我要找的,我想在我的自定義應用程序的urls.py中保留所有URL路由。

+1

不要嘗試。使用顯式名稱。無論如何,不​​推薦在URL中使用字符串視圖路徑。 –

回答

0

您已經添加了一個命名空間,所以你需要正確地解析URL(指documentation詳細介紹):

reverse('shop:product_index') 

很顯然,我不想使用命名空間中這個案例。如果您閱讀我的 問題,我想通過函數名稱來調用它,當 將路由放在demostore/demostore/urls.py文件中時,該函數名稱正在工作。但不包含在 包含的lindshop/urls.py文件中。是的,它可以與 反向('shop:product_index')配合使用。但那不是我想要的。

如果你讀了documentation for reverse,你會發現這個片段:

使用Python路徑逆轉的能力,例如:

自1.8版本棄用 reverse('news.views.archive')已被棄用。

+0

反向('lindshop:product_index')認爲應用程序名稱是lindshop。 –

+0

顯然我不想在這種情況下使用命名空間。如果你閱讀我的問題,我想通過函數名稱來調用它,當我將路由放在demostore/demostore/urls.py文件中時,該函數名稱正在工作。但不包括在lindshop/urls.py文件中。 是的......它可以與'reverse('shop:product_index')'配合使用。但那不是我想要的。 –