Simon
Simon

Reputation: 171

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.

Upvotes: 17

Views: 27265

Answers (6)

davidjbrady
davidjbrady

Reputation: 71

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

Upvotes: 5

neatsoft
neatsoft

Reputation: 359

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

Upvotes: 21

dev
dev

Reputation: 411

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

Upvotes: 4

Kim Stacks
Kim Stacks

Reputation: 10812

This works for me. The reverse_lazy did not.

Django 1.8.1 and above

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

Upvotes: 4

Mariusz Jamro
Mariusz Jamro

Reputation: 31633

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

Upvotes: 17

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

Upvotes: 9

Related Questions