menu

Questions & Answers

Redirect to the main page if authenticated

I got some problems with redirecting.

When I already logged in, and try go to "/accounts/login", it still goes to this link, and if I change in url.py path for example "accounts/logins", the redirect is working, but if not authenticated it says me that:

UnboundLocalError: local variable 'context' referenced before assignment

AND "/accounts/login" is still available

views.py

def loginPage(request):
    if request.user.is_authenticated:
        return redirect("index")
    if request.method == 'POST':
            username = request.POST.get('username')
            password = request.POST.get('password')

            user = authenticate(request, username=username, password=password)

            if user is not None:
                login(request, user)
                return redirect('index')
            else:
                messages.info(request, 'Username OR password is incorrect')
            context = {}

    return render(request, 'registration/login.html', context)

url.py

urlpatterns = [
    path('login/', views.loginPage, name='loginPage'),
    path('logout/', views.logoutUser, name='logoutUser'),
    path('register/', views.registerPage, name='registerPage'),
]
Answers(1) :

In order to redirect to an specific url once logged in you can set in your settings.py the following:

LOGIN_REDIRECT_URL = '/'

hope this is what are you looking for