Login

newforms self-contained login form

Author:
miracle2k
Posted:
July 20, 2007
Language:
Python
Version:
.96
Score:
9 (after 11 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 3 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months 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

#

Please login first before commenting.