Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Redirect already logged user by class based view

I want to redirect to the main page if the user is already authenticated. So I want a redirect from / to /main

views.py:

class LoginView(FormView):
    form_class = LoginForm
    success_url = reverse_lazy('main')
    template_name = 'module/login.html'

    def form_valid(self, form):

        if self.request.user.is_authenticated():
            return redirect(settings.LOGIN_REDIRECT_URL)
        else:
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)

            if user is not None and user.is_active:
                login(self.request, user)
                return super(LoginView, self).form_valid(form)
            else:
                return self.form_invalid(form)

settings.py:

LOGIN_REDIRECT_URL = reverse_lazy('main')
LOGIN_URL = reverse_lazy('login')
LOGOUT_URL = reverse_lazy('logout')

I tried also to add a get function, but then it call itself only infinite times.

def get(self, request, *args, **kwargs):

    if request.user.is_authenticated():
        return HttpResponseRedirect('main')
    else:
        return HttpResponseRedirect('/login/')

urls.py:

url(r'^$', views.LoginView.as_view(), name='login'),
url(r'^login/', views.LoginView.as_view(), name='login'),
like image 380
ikreb Avatar asked Jan 17 '17 13:01

ikreb


3 Answers

You do redirect to the view itself in the else part, hence the infinite redirect loop. Do instead:

def get(self, request, *args, **kwargs):
    if request.user.is_authenticated():
        return HttpResponseRedirect('main')
    return super(LoginView, self).get(request, *args, **kwargs)

you should also rename the first of your two views in urls.py to 'main'.

like image 58
user2390182 Avatar answered Oct 08 '22 17:10

user2390182


If your app is Django 2.x or 3.x then this is the way.

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

urlpatterns = [
    path('login/', auth_views.LoginView.as_view(redirect_authenticated_user=True), name='login'),
]
like image 22
Shobi Avatar answered Oct 08 '22 17:10

Shobi


I couldn't get any of these solutions to work for what I needed so I'll post my working solution here. In my view I used redirect and render, both imported from django.shortcuts.

class ManagementPageView(TemplateView):

    # Make a dispatch method to handle authentication
    def dispatch(self, *args, **kwargs):

        # Check if user is authenticated 
        if not self.request.user.is_authenticated:

            # Redirect them to the home page if not 
            return redirect('home')
            
        # Render the template if they are 
        return render(self.request, 'management.html')
like image 23
Casivio Avatar answered Oct 08 '22 17:10

Casivio