sll1kw
Last Updated: December 01, 2017
·
13.22K
· getmoneydouble
24edbd185da68e27c5e6d26a52fc7dc9

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)
Say Thanks
Respond

4 Responses
Add your response

13632
0d66a8cb02221feb7198fde2fdf04d32

FUCK you this doesn't work!!!

over 1 year ago ·
13633
24edbd185da68e27c5e6d26a52fc7dc9

It should work fine..

over 1 year ago ·
23084
A42473434821fe7fec7b9cc58d1cc087

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

over 1 year ago ·
28036

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 ·