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
.
views.py
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():
self.request.session.delete_test_cookie()
return HttpResponseRedirect(redirect_to)
def form_invalid(self, form):
return self.render_to_response(self.get_context_data(form=form))
@method_decorator(sensitive_post_parameters('password'))
def dispatch(self, request, *args, **kwargs):
request.session.set_test_cookie()
return super(Login, self).dispatch(request, *args, **kwargs)
class Logout(View):
def get(self, request, *args, **kwargs):
auth_logout(request)
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!
Written by Keith
Related protips
3 Responses
Thank you! Very terse and clean.
A couple of issues:
- the
auth_login
andrender_to_response
lines are missing the closing bracket. - the
sensitive_post_parameters
import is missing the wordfrom
. -
resolve_url
is not imported. (I think it should be fromdjango.shortcuts
.) -
FormView, View
should be imported fromdjango.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!
Thanks for catching those! I've updated the protip. Good luck on your project!
Hi i tried to use it but not working, always go inside form_invalid here is my form.py http://hastebin.com/ivulalebav.vhdl and here is my views.py http://hastebin.com/etudipofeg.py can u help me? Sorry about my bad English
Do u have a complete example? Thanks a lot