[Fixed]-How can I use a catch all route using `path` or `re_path` so that Django passes all unmatched requests to my index view?

10👍

So as I said in the question description, trying the regex I was using before Django 2.0 in re_path did not work. It would basically match for all requests except / (i.e., index path). I fixed this by using both that regex and a second path matching / specifically. Here’s the code:

urlpatterns = [
    re_path(r'^(?P<path>.*)/$', IndexView.as_view()),
    path('', IndexView.as_view()),
]

With these changes my other routes would match and these two routes would account for all other urls.

14👍

You can use two entries (one for ‘/’, another one for anything else), but using path for both of them, which should be (slightly) more efficient:

urlpatterns = [
    path('', IndexView.as_view(), {'resource': ''}),
    path('<path:resource>', IndexView.as_view())
]

In this case, I’m using <path:resource> because path catches all resource names, inluding that with / in them. But it does not capture the main index resource, /. That’s why the first entry. The dictionary as last argument for it is because we need to provide a resource parameter if we want to use the same view than in the second entry.

That view, of course, should have ‘resource’ as a paremeter:

def as_view(request, resource):
   ...

7👍

One Idea to go about this is let the django catch 404.

url.py

from django.conf.urls import handler404

handler404 = 'app_name.views.bad_request'

and in your views.py

views.py

def bad_request(request):
    return redirect(reverse('home'))

You can always do some regex thingy to catch unmatched urls. but hey this gets the job done. 🙂

Leave a comment