Django 将所有未捕获的 url 路由到包含 urls.py

Django route all non-catched urls to included urls.py

我希望每个不以 'api' 开头的 url 都使用 foo/urls.py

urls.py

from django.conf.urls import include, url
from foo import urls as foo_urls

urlpatterns = [
url(r'^api/', include('api.urls', namespace='api')),
url(r'^.*/$', include(foo_urls)),
]    

foo/urls.py

from django.conf.urls import include, url
from foo import views

urlpatterns = [
url(r'a$', views.a),
]    

这行不通,知道吗?

如果您想要捕获所有 url 模式,请使用:

url(r'^', include(foo_urls)),

来自the docs

Whenever Django encounters include() it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.

在您当前的代码中,正则表达式 ^.*/$ 匹配整个 url /a/。这意味着没有任何东西可以传递给 foo_urls.

这样做:

urlpatterns = [
url(r'^api/', include('api.urls', namespace='api')),
url(r'^', include(foo_urls)),
]