确保urlpatterns是path()和/或re_path()实例的列表

时间:2018-05-11 18:36:59

标签: python django python-3.x

我的urlpatterns出了什么问题?

urlpatterns = [
    re_path(r'^dj-admin/', admin.site.urls),
    re_path(r'^admin/', include(wagtailadmin_urls)),
    re_path(r'^docs/', include(wagtaildocs_urls)),

    i18n_patterns(
        path(r'', include(wagtail_urls)),
        prefix_default_language = False
    )
]
  

错误:
  ?:( urls.E004)您的网址格式[(无:无)''>]无效。确保urlpatterns是path()和/或re_path()实例的列表。

据我所知,它等同于docs中的示例:

urlpatterns = [
    path('sitemap.xml', sitemap, name='sitemap-xml'),
]

urlpatterns += i18n_patterns(
    path('about/', about_views.main, name='about'),
)

顺便说一句:

In [1]: import django

In [2]: django.__version__
Out[2]: '2.0.5'

1 个答案:

答案 0 :(得分:2)

您已将i18n_patterns 放在模式列表中,但此函数本身会生成urlpatterns列表,而不是单个模式。这与您找到的文档不同。

使用连接:

urlpatterns = [
    re_path(r'^dj-admin/', admin.site.urls),
    re_path(r'^admin/', include(wagtailadmin_urls)),
    re_path(r'^docs/', include(wagtaildocs_urls)),
] + i18n_patterns(
    path(r'', include(wagtail_urls)),
    prefix_default_language = False
)

或使用*为函数调用添加前缀,以将所有元素合并到列表中:

urlpatterns = [
    re_path(r'^dj-admin/', admin.site.urls),
    re_path(r'^admin/', include(wagtailadmin_urls)),
    re_path(r'^docs/', include(wagtaildocs_urls)),

    *i18n_patterns(
        path(r'', include(wagtail_urls)),
        prefix_default_language = False
    )
]

这称为iterable unpacking,需要Python 3.5或更高版本。

文档使用+=扩充分配扩展 urlpatterns列表,这可能是一个很好的模式供您重复使用:

urlpatterns = [
    re_path(r'^dj-admin/', admin.site.urls),
    re_path(r'^admin/', include(wagtailadmin_urls)),
    re_path(r'^docs/', include(wagtaildocs_urls)),
]

urlpatterns += i18n_patterns(
    path(r'', include(wagtail_urls)),
    prefix_default_language = False
)