1

Is it possible to define a route that will be redirected to if Django could not find a match in the defined URLs?

For example, let's say I have:

urlpatterns = [
    path('ajaxlogin', views.ajax_login, name='ajaxlogin'),
    path('ajaxprofile', views.ajax_profile, name='ajaxprofile'),
]

Can I define a "dynamic" URL of a specific view that will be redirected to if the path doesn't exist? Suppose I enter the URLs /ajaxsignup and /ajaxdelete, which are not defined, but have them redirected to a URL of a certain view?

In other words:

urlpatterns = [
    path('ajaxlogin', views.ajax_login, name='ajaxlogin'),
    path('ajaxprofile', views.ajax_profile, name='ajaxprofile'),
    path('every-other-url', views.another_view, name='path-everything-else'),
]

I know there's Django's error handlers, but are there any other ways to achieve this? I have my frontend based separately on a React application, so I'd very much appreciate a "dynamic" URL rather than using Django's default 404 responses.

I suspect that if path couldn't do it, I could use the old url with regex -- but I still have no clue.

Thanks in advance.

crimsonpython24
  • 2,223
  • 2
  • 11
  • 27
  • wouldn't re_path work with a wildcard at the end of your urlpatterns list? – Trent Jun 04 '21 at 02:30
  • @Trent can you please elaborate (or probably post a documentation link or something)? – crimsonpython24 Jun 04 '21 at 02:30
  • Yeah I found the documentation [here](https://docs.djangoproject.com/en/3.2/ref/urls/#re-path), but can you please tell me how to exclude the two defined URLs above? Or will `re_path` handle that? – crimsonpython24 Jun 04 '21 at 02:33

1 Answers1

3

Just add a wildcard re_path at the end of your urlpatterns:

from django.http import HttpResponse
from django.urls import re_path

def http_response(request):
    return HttpResponse('<h1>Hello HttpResponse</h1>')

urlpatterns = [
    path('ajaxlogin', views.ajax_login, name='ajaxlogin'),
    path('ajaxprofile', views.ajax_profile, name='ajaxprofile'),
    path('every-other-url', views.another_view, name='path-everything-else'),
    re_path(r'.*', http_response), # only if the above routes don't trigger a match
]

It processes routes in order, so if it doesn't find a route before it hits the wildcard, it will return that one.

Trent
  • 2,909
  • 1
  • 31
  • 46