newforms self-contained login form

 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

  1. LoginAsForm - Login as any User without a password by johnboxall 4 years, 10 months ago
  2. Admin Image Widget by baumer1122 5 years, 8 months ago
  3. Get the referer view of a request by arthurfurlan 4 years, 11 months ago
  4. SectionedForm by marinho 5 years, 10 months ago
  5. FieldsetForm by Ciantic 7 years ago

Comments

sweecoo (on August 3, 2007):

Nice, although it does not clear the password if it is incorrect.

#

rcoup (on August 27, 2007):

There is a minor typo in the example view:

if loginform.login():

should be

if loginform.login(request):

#

MikeHowarth (on September 10, 2007):

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'

#

nipuL (on May 30, 2008):

The clean method should return self.cleaned_data

#

(Forgotten your password?)