[Fixed]-Redirect request to admin interface

20👍

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),
]

17👍

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')))

9👍

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'))

5👍

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),
    ...
] 

4👍

This works for me. The reverse_lazy did not.

Django 1.8.1 and above

urlpatterns = patterns('',
    url(r'^$', lambda x: HttpResponseRedirect('/admin')),
)

4👍

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'),
)
👤dev

Leave a comment