Last Updated: February 25, 2016
· keithio

Class-based Authentication Views

I strongly feel that the direction in which Django is moving is correct. For those of you not already using class-based views (CBV), read up on them and start using them. They seriously rock.

The problem is that some of the built-in views are still function-based. In an effort to make everything on my most recent project 100% CBV-based, I slightly rewrote some of the djanago.contrib.auth.views.

from django.conf import settings
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login as auth_login, logout as auth_logout
from django.http import HttpResponseRedirect
from django.utils.decorators import method_decorator
from django.views.decorators.debug import sensitive_post_parameters
from django.views import FormView, View

class Login(FormView):
    form_class = AuthenticationForm

    def form_valid(self, form):
        redirect_to = settings.LOGIN_REDIRECT_URL
        auth_login(self.request, form.get_user())
        if self.request.session.test_cookie_worked():
        return HttpResponseRedirect(redirect_to)

    def form_invalid(self, form):
        return self.render_to_response(self.get_context_data(form=form))

    def dispatch(self, request, *args, **kwargs):
        return super(Login, self).dispatch(request, *args, **kwargs)

class Logout(View):
    def get(self, request, *args, **kwargs):
        return HttpResponseRedirect(settings.LOGOUT_REDIRECT_URL)

Now you can use these views like any other class-based view, e.g. Login.as_view() in your url patterns!

3 Responses
Add your response

Thank you! Very terse and clean.

A couple of issues:

  • the auth_login and render_to_response lines are missing the closing bracket.
  • the sensitive_post_parameters import is missing the word from.
  • resolve_url is not imported. (I think it should be from django.shortcuts.)
  • FormView, View should be imported from django.views.generic

Nothing major, really, just thought you might want to update the code. Anyway! I plan to use a derivitive of this in my project, so thanks again!

over 1 year ago ·

Thanks for catching those! I've updated the protip. Good luck on your project!

over 1 year ago ·

Hi i tried to use it but not working, always go inside form_invalid here is my and here is my can u help me? Sorry about my bad English
Do u have a complete example? Thanks a lot

over 1 year ago ·