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):
...
- Django โ async_to_sync vs asyncio.run
- Django makemigrations not detecting project/apps/myapp
- How could one disable new account creation with django-allauth, but still allow existing users to sign in?
- How does a Django UUIDField generate a UUID in Postgresql?
- Create a canonical "parent" product in Django Oscar programmatically
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. ๐