简体   繁体   中英

How do I redirect away from the login page, if the user is already logged in and goes to login page in Django?

I'm using built in authentication system of Django 2.1.

URL file paths in urls.py file.

urlpatterns = [
        path('',include('rmcapp.urls')),
        path('admin/', admin.site.urls),
        path('accounts/', include('django.contrib.auth.urls')),
      ]

Login.html path = " templates/registration/login.html Using

<form method="post" action="{% url 'login' %}"> 

as form tag in login.html file.

I haven't extended LoginView class in views.py file (If it is necessary then i'll extend)

I tried this in urls.py file

url(r'^login/$', LoginView.as_view(redirect_authenticated_user=True)),

but it didn't worked.

Example Case: User logs in by providing his credentials, once he is directed to the home page and presses browser's back button he'll land in the login page again. It'll again ask for the credentials but actually the user is already logged in. How do we redirect the user to the home page in this case?

If you're using the LoginView provided by Django, you'll see that it accepts a parameter, redirect_authenticated_user , that allows you to tell the login view to redirect if the user is already logged in.

However, this behavior is not really secure (as explained in the warning). And it's not really necessary. It's quite normal for a website to just display the login form even if a user is already logged in when explicitly going to that page.

What you probably want, is that your login view redirects to the page the user requested before asked to login rather than the home page (so the user doesn't have to go back).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM