'Redirect request to admin interface
After enabling the administrator interface and starting the development web server on e.g. 128.0.0.1:8000, I am able to reach the admin interface on
128.0.0.1:8000/admin.
Obviously due the following URL namespace
url(r'^admin/', include(admin.site.urls)).
What do I have to do redirect requests on 128.0.0.1:8000/ automatically to 128.0.0.1:8000/admin?
The URL namespace
url(r'^$/', include(admin.site.urls))
does not seem to be the solution.
Solution 1:[1]
Use RedirectView. Instead of hardcoding URLs you can use reverse and the name of an admin view.
from django.core.urlresolvers import reverse
from django.views.generic.base import RedirectView
url(r'^$', RedirectView.as_view(url=reverse('admin:index')))
Solution 2:[2]
Django 2.0 and above:
from django.contrib import admin
from django.urls import path, reverse_lazy
from django.views.generic.base import RedirectView
urlpatterns = [
path('', RedirectView.as_view(url=reverse_lazy('admin:index'))),
path('admin/', admin.site.urls),
]
Solution 3:[3]
You say you want a redirect so you would use django's RedirectView
from django.views.generic.base import RedirectView
url(r'^$', RedirectView.as_view(url='/admin'))
Solution 4:[4]
This works for me. The reverse_lazy did not.
Django 1.8.1 and above
urlpatterns = patterns('',
url(r'^$', lambda x: HttpResponseRedirect('/admin')),
)
Solution 5:[5]
Previous solutions either show redirection to a hard-coded URL or use methods that didn't work here. This one works in Django 1.9 and redirects to the admin index view:
from django.shortcuts import redirect
urlpatterns = patterns('',
url(r'^$', lambda _: redirect('admin:index'), name='index'),
)
Solution 6:[6]
You can also use path instead of url which has been deprecated and is no longer available in Django 4.
from django.views.generic.base import RedirectView
urlpatterns = [
path('', RedirectView.as_view(url='/admin')),
path('admin/', admin.site.urls),
...
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chriki |
| Solution 2 | neatsoft |
| Solution 3 | |
| Solution 4 | |
| Solution 5 | Scholtalbers |
| Solution 6 | davidjbrady |
