Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set custom admin login URL in Django Admin on session timeout?

I wrote a Django app which has an external authentication system reacheable at some URL (say, https://.../myproject/login). This is working well.

However, when the session expires, the user gets redirected to the default login url which is https://.../myproject/admin). I'd like to change the behavior of the app so if the session expires, the user should be redirected to https://.../myproject/login and only use the /admin login when explicitly opened.

Is there a built-in way to do this in Django?

like image 760
nKn Avatar asked Jan 26 '23 08:01

nKn


1 Answers

Django admin redirects the users to /admin/login when the session is expired or session is missing.

There are several ways to redirect users to https://.../myproject/login instead of https://.../myproject/admin/login.

Approach 1:

Override the view of myproject/admin/login URL with the view of myproject/login.

Let's say that myproject/login uses LoginView to render external system's login page, then add url(r'^admin/login/?$', LoginView.as_view(), name='admin:login') just above url(r'^admin/', include(admin.site.urls)) in myproject/myproject/urls.py

urlpatterns = [
   url(r'^admin/login/?$', LoginView.as_view(), name='admin:login'),
   url(r'^admin/', include(admin.site.urls)),
]

Pros:

  • Render the external system's login page instead of default Django admin login page on /myproject/admin/login

Cons:

  • The URL still points to myproject/admin/login
  • No way to access the default admin login page

Approach 2:

Override the view of myproject/admin/login url and redirect the user to myproject/login

Lets create a new view AdminLoginView then add url(r'^admin/login/?$', AdminLoginView.as_view(), name='admin:login') just above url(r'^admin/', include(admin.site.urls)) in myproject/myproject/urls.py

from django.core.urlresolvers import reverse

class AdminLoginView(TemplateView):
    def get(self, request, *args, **kwargs):
        """
        Assuming the name of the external system's login url is "login"
        """
        return HttpResponseRedirect(reverse('login'))

urlpatterns = [
   url(r'^admin/login/?$', AdminLoginView.as_view(), name='admin:login'),
   url(r'^admin/default-login/?$', admin.site.login, name='default-admin-login'),
   url(r'^admin/', include(admin.site.urls)),
]

Pros:

  • The URL changes to myproject/login

Cons:

  • You have to add extra code for the default login page.

I would recommend approach 2 to solve the problem mentioned in the question.

Thanks.

like image 198
sun_jara Avatar answered Jan 29 '23 10:01

sun_jara