Home > Software engineering >  Redirect to the main page if authenticated
Redirect to the main page if authenticated

Time:01-20

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 if I remove it in url.py

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

CodePudding user response:

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

CodePudding user response:

Try this code...

def loginPage(request):
    
    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')
            return redirect('/login/')
    else:
        if request.user.is_authenticated:
            return redirect('/index/')
        else:
            context = {}
            return render(request, 'registration/login.html',context)
  • Related