2015-10-13 13 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')'配合使用。但那不是我想要的。 –