Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django redirect preserving subpath

Tags:

python

django

In my urls.py I have:

urlpatterns = [
    url(r'^admin/', admin.site.urls, name='admin'),
    url(r'^django-admin/', RedirectView.as_view(url='/admin/', permanent=True)),
]

So if I go to localhost:8000/django-admin/ it successfully redirects me to localhost:8000/admin/, and if I go to localhost:8000/django-admin/my-app/ it also redirects me to localhost:8000/admin/.

How could I make localhost:8000/django-admin/my-app/ go to localhost:8000/admin/my-app/? And the same for every possible subpath e.g. localhost:8000/django-admin/my-app/my-view, localhost:8000/django-admin/another-app/, etc?

like image 953
damores Avatar asked Apr 24 '26 14:04

damores


1 Answers

According to the docs something like this should work, you can capture groups from the path and pass them to the url

The given URL may contain dictionary-style string formatting, which will be interpolated against the parameters captured in the URL. Because keyword interpolation is always done (even if no arguments are passed in), any "%" characters in the URL must be written as "%%" so that Python will convert them to a single percent sign on output.

url(r'^django-admin/(?P<rest>.*)', RedirectView.as_view(url='/admin/%(rest)s', permanent=True)

This website is particularly useful for figuring out how the built-in class-based views work http://ccbv.co.uk/projects/Django/2.2/django.views.generic.base/RedirectView/#get_redirect_url

like image 181
Iain Shelvington Avatar answered Apr 26 '26 02:04

Iain Shelvington