Django route all non-catched urls to included urls

2019-06-21 18:43发布

问题:

I want every url that does not start with 'api' to use the 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),
]    

This does not work, any idea ?

回答1:

If you want a catch all url pattern, use:

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

From 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.

In your current code, the regex ^.*/$ matches the entire url /a/. This means that there is nothing remaining to pass to foo_urls.



回答2:

do this:

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