Django 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
31
32
33
34
35
36
37
38
39
40
class NextUrlField(forms.CharField):
widget = forms.HiddenInput
def __init__(self, *args, **kwargs):
super(NextUrlField, self).__init__(*args, **kwargs)
self.required = False
def clean(self, value):
if not value:
return getattr(settings, 'LOGIN_REDIRECT_URL', '/')
else:
return value
class LoginForm(forms.Form):
username = User._meta.get_field('username').formfield()
password = User._meta.get_field('password').formfield(widget=forms.PasswordInput)
next = NextUrlField()
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
self.base_fields['username'].help_text = ''
#self.base_fields['password'].widget = forms.PasswordInput()
self.base_fields['password'].help_text = ''
self.base_fields['next'] = NextUrlField()
super(LoginForm, self).__init__(*args, **kwargs)
def clean(self):
super(LoginForm, self).clean()
if self.is_valid():
user = authenticate(
username=self.cleaned_data['username'],
password=self.cleaned_data['password'])
if not user is None:
if user.is_active:
login(self.request, user)
return self.cleaned_data
else:
raise forms.ValidationError(_("Sorry. Your account is not active. Most likely is that you didn't confirm your registration"))
else:
raise forms.ValidationError(_('Wrong username or password'))