Last Updated: June 14, 2018
·
32.91K
· getmoneydouble

Django Auth Class-Based-Views Login and Logout

Django Class-Based-Views Auth. Allows you to use CBV's for Login and Logout functionality instead of the FBV's provided by django.contrib.auth

from django.utils.http import is_safe_url
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import REDIRECT_FIELD_NAME, login as auth_login, logout as auth_logout
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic import FormView, RedirectView


class LoginView(FormView):
    """
    Provides the ability to login as a user with a username and password
    """
    success_url = '/auth/home/'
    form_class = AuthenticationForm
    redirect_field_name = REDIRECT_FIELD_NAME

    @method_decorator(sensitive_post_parameters('password'))
    @method_decorator(csrf_protect)
    @method_decorator(never_cache)
    def dispatch(self, request, *args, **kwargs):
        # Sets a test cookie to make sure the user has cookies enabled
        request.session.set_test_cookie()

        return super(LoginView, self).dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        auth_login(self.request, form.get_user())

        # If the test cookie worked, go ahead and
        # delete it since its no longer needed
        if self.request.session.test_cookie_worked():
            self.request.session.delete_test_cookie()

        return super(LoginView, self).form_valid(form)

    def get_success_url(self):
        redirect_to = self.request.REQUEST.get(self.redirect_field_name)
        if not is_safe_url(url=redirect_to, host=self.request.get_host()):
            redirect_to = self.success_url
        return redirect_to


class LogoutView(RedirectView):
    """
    Provides users the ability to logout
    """
    url = '/auth/login/'

    def get(self, request, *args, **kwargs):
        auth_logout(request)
        return super(LogoutView, self).get(request, *args, **kwargs)

6 Responses
Add your response

FUCK you this doesn't work!!!

over 1 year ago ·

It should work fine..

over 1 year ago ·

I works fine, the only thing that you need to add is the var template_name.

over 1 year ago ·

Works fine for me. Thanks for the snippet :-)
As already stated you have to add template_name.

For Django 1.9+ change the line
redirectto = self.request.REQUEST.get(self.redirectfieldname)
to
redirect
to = self.request.GET.get(self.redirectfieldname)

over 1 year ago ·

Perfect thank you!

over 1 year ago ·

Looks really great! I also had to change redirect_to = self.request.REQUEST.get(self.redirect_field_name) to redirect_to = self.request.GET.get(self.redirect_field_name)

over 1 year ago ·