How to authenticate session inside class based view django

I am new to Django

I am trying to convert my function-based views to class-based views. Here I ran into a problem.

I don’t know whether the user is logged in or not. I can’t call the user.is_authenticated inside my class-based view.

My Code:

class UserLoginView(FormView):
    template_name = 'login.html'
    form_class = UserLoginForm
    success_url = reverse_lazy('login')

    def form_valid(self, form):
        user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'])
        if user is not None:
            login(request=self.request, user=user)
            print('Login Successfull')
            return HttpResponseRedirect(self.success_url)

    def form_invalid(self, form):
        print('Login Failed')
        return HttpResponseRedirect(self.success_url)

How can I check whether the user is already logged in and send him directly to the home page.

Thanks in advance.


As your requirement, you want to authenticate a user and send them to the home page after logged-in in a class-based view.

Here is what we can do. We can use the LoginRequiredMixin in your class-based home page view to help us to check is a user logged-in. If a user is not logged-in, they will be redirected to a login page we specified. Otherwise, execute the view normally and the user will be free to access the home page.



from django.contrib.auth.mixins import LoginRequiredMixin

class HomeView(LoginRequiredMixin):  # Add the LoginRequiredMixin 
    template_name = 'index.html'
    login_url = '/login/'  # Replace '/login/' with your login URL, an un-logged-in user will be redirect to this URL

One thing must care about while using the LoginRequiredMixin is the ordering.

Mostly we put the LoginRequiredMixin in the first position of inheritance if our class-based view inherited multiple classes. Because it makes sure the user is logged-in before the view does anything further for the user.

class HomeView(LoginRequiredMixin, ClassA, ClassB):

You can get more information about LoginRequiredMixin in this page

Leave a Reply

Your email address will not be published. Required fields are marked *