Django re_path to catch all URLs except /admin/ not working properly
I'm trying to define a re_path in Django that catches all URLs except those that start with /admin/. My goal is to redirect unknown URLs to a custom view (RedirectView), while ensuring that all admin URLs (including subpaths like /admin/mymodel/something/) are excluded.
from django.urls import re_path, path
from django.contrib import admin
from . import views
urlpatterns = [
path('admin/', admin.site.urls), # Ensure Django admin URLs are handled
]
# Catch-all pattern that should exclude /admin/ URLs
urlpatterns += [
re_path(r"^.*/(?!admin/$)[^/]+/$", views.RedirectView.as_view(), name="my-view"),
]
Issue:
URLs like localhost:8000/admin/mymodel/something/ are correctly ignored, which is good.
However, single-segment URLs like localhost:8000/something/ are not being matched, even though they should be redirected.
adjust your re_path that should exclude /admin/ URLs
urlpatterns += [
re_path(r"^(?!admin/).*", views.RedirectView.as_view(), name="my-view"),
]