反向查看功能无法使用多个urls.py文件

时间:2015-10-13 07:45:40

标签: python django

我在使用reverse()函数和视图函数作为参数时遇到问题。当我在默认的urls.py文件中指定URL路由时,它工作正常。但是当我有一个import到辅助urls.py文件时,我会收到NoReverseMatch - 错误。

所以...这就是我的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中保留所有网址路由。

1 个答案:

答案 0 :(得分:0)

您添加了名称空间,因此需要正确解析网址(有关详细信息,请参阅documentation):

reverse('shop:product_index')
  

显然我不想在这种情况下使用Namespace。如果你读了我的   问题我想通过函数名称来调用它,当我工作时它正在工作   将路由放在demostore / demostore / urls.py文件中。但不是   包含lindshop / urls.py文件。是的......它确实有效   反向('店:PRODUCT_INDEX&#39)。但那不是我想要的。

如果您阅读了documentation for reverse,则会找到以下代码段:

  

自1.8版以来不推荐使用:

     

使用Python路径反转的能力,例如   反向(' news.views.archive')已被弃用。

相关问题