A simple login form that does the actual authentification itself.
Usage:
if request.method == "POST":
loginform = LoginForm(request.POST)
if loginform.login():
return HttpResponseRedirect(redir_url)
else:
loginform = LoginForm()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | from django.utils.translation import ugettext_lazy as _, ugettext
from django import newforms as forms
class LoginForm(forms.Form):
username = forms.CharField(label=_('username'))
password = forms.CharField(label=_('password'))
user = None # allow access to user object
def clean(self):
# only do further checks if the rest was valid
if self._errors: return
from django.contrib.auth import login, authenticate
user = authenticate(username=self.data['username'],
password=self.data['password'])
if user is not None:
if user.is_active:
self.user = user
else:
raise forms.ValidationError(ugettext(
'This account is currently inactive. Please contact '
'the administrator if you believe this to be in error.'))
else:
raise forms.ValidationError(ugettext(
'The username and password you specified are not valid.'))
def login(self, request):
from django.contrib.auth import login
if self.is_valid():
login(request, self.user)
return True
return False
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 12 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
Nice, although it does not clear the password if it is incorrect.
#
There is a minor typo in the example view:
if loginform.login():
should be
if loginform.login(request):
#
Struggling to get this snippet running.
Using Django 0.96 I'm getting the following errors:
Traceback:
Traceback (most recent call last): File "C:\Python25\lib\site-packages\django\core\handlers\base.py" in get_response 77. response = callback(request, callback_args, *callback_kwargs) File "D:\Web Dev\Test\eshop..\eshop\login\views.py" in login 10. if loginform.login(request): File "D:\Web Dev\Test\eshop..\eshop\login\forms.py" in login 56. login(request, self.user) File "C:\Python25\lib\site-packages\django\contrib\auth__init__.py" in login 53. request.session[BACKEND_SESSION_KEY] = user.backend
AttributeError at /login/ 'User' object has no attribute 'backend'
#
The clean method should return self.cleaned_data
#
Please login first before commenting.