6

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 ?

yossi
  • 12,945
  • 28
  • 84
  • 110

2 Answers2

13

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.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • 1
    You don't need the `^` you can just do `url('', include(foo_urls)),` – Boris Verkhovskiy Jul 26 '20 at 23:16
  • @Boris yes, `url(r'^', include(...))` and `url('', include(...))` will behave the same in this case, but in general, the `^` does make a difference. For example `url('blog/', include(...))` will match `weblog/` but `url(r'^blog/', include(...))` will not. If you're using `url()` or `re_path`, then I'd recommend using `r'^'` for consistency. The easiest solution might be to switch to `path()` and use `path('', include(...))`. – Alasdair Jul 27 '20 at 09:32
3

do this:

urlpatterns = [
url(r'^api/', include('api.urls', namespace='api')),
url(r'^', include(foo_urls)),
]  
Ajay Gupta
  • 1,285
  • 8
  • 22