Search code examples
djangopython-3.xdjango-viewsdjango-authenticationdjango-registration

how can I prevent user to go to login page after successful authentication?


I am adding settings.py, root url and views.py. After login user is redirected to respective dashboard. In this situation, if user is pressing back button or changing url to accounts/login, then also it should remain on the dashboard page only. I am using django-registration-redux

settings.py

REGISTRATION_OPEN = True
ACCOUNT_ACTIVATION_DAYS = 7
REGISTRATION_AUTO_LOGIN = False
REGISTRATION_FORM = 'signin.forms.MyRegForm'
LOGIN_REDIRECT_URL = '/signin/user_sign/'

views.py

def user_sign(request):
    obj = UserSelection.objects.get(user=request.user)

    if obj.user_type == 'candidate':
        return redirect('candidate:cand_dash')

    else:
        return redirect('employer:employer_dash')

urls.py

from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from signin.regbackend import MyRegistrationView
from django.contrib.auth import views as auth_views

urlpatterns = [
    url(r'^$', auth_views.LoginView.as_view(template_name='registration/login.html'), name='home'),
    url(r'^accounts/register/$', MyRegistrationView.as_view(), name='registration_register'),
    url(r'^accounts/', include('registration.backends.default.urls')),

    url(r'^candidate/', include('candidate.urls')),
    url(r'^employer/', include('employer.urls')),
    url(r'^signin/', include('signin.urls')),
]

Solution

  • You could use a Boolean variable authenticated.

    Then you should need to set it as False before the user Authentication.

    def registration(request):
        authenticated = False
    ...
    

    Then after the user's authentication just change the var as authenticated = True

    Finally every time you need to know if user is authenticated just use if user.authenticated

    Also, if you need to use authenticated a lot take a look at custom decorators (https://docs.djangoproject.com/en/2.0/topics/http/decorators/) maybe they could help you.