How to authenticate session inside class based view django

  django, django-forms, django-models, python, python-3.x

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.

Source: Python-3x Questions

LEAVE A COMMENT