[Fixed]-How to prevent user to access login page in django when already logged in?



You can redirect users by modifying your urls.py file like below:

from django.urls import path
from django.contrib.auth import views as auth_views
from . import views

app_name = 'account'

urlpatterns = [
  path('signup/', views.register, name='register'),
  path('', auth_views.LoginView.as_view(redirect_authenticated_user=True), name='login'),

This will redirect already authenticated users from the login page.
For the signup you will have to customize your register function add an if user is authenticated check.



You can use this decorator as well.

def login_excluded(redirect_to):
    """ This decorator kicks authenticated users out of a view """ 
    def _method_wrapper(view_method):
        def _arguments_wrapper(request, *args, **kwargs):
            if request.user.is_authenticated:
                return redirect(redirect_to) 
            return view_method(request, *args, **kwargs)
        return _arguments_wrapper
    return _method_wrapper

Then call it in your views.py.

def someview(request):
    # ...

Leave a comment