Ticket #10763: login_custom_form-forms.py

File login_custom_form-forms.py, 1.7 KB (added by Felipe 'chronos' Prenholato, 15 years ago)

The form in forms.py that I using, basically a copy of AuthenticationForm

Line 
1class MyAuthenticationForm(BetterForm):
2 """
3 Base class for authenticating users. Extend this to get a form that accepts
4 username/password logins.
5 """
6 username = forms.CharField(label=_("Username"), max_length=30)
7 password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
8
9 class Meta:
10
11 fieldsets=((u'login',{'fields':('username','password'),'legend':'','description':_("Please, enter with your username and password:")}),)
12
13 def __init__(self, request=None, *args, **kwargs):
14 """
15 If request is passed in, the form will validate that cookies are
16 enabled. Note that the request (a HttpRequest object) must have set a
17 cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
18 running this validation.
19 """
20 self.request = request
21 self.user_cache = None
22 super(MyAuthenticationForm, self).__init__(*args, **kwargs)
23
24 def clean(self):
25 username = self.cleaned_data.get('username')
26 password = self.cleaned_data.get('password')
27
28 if username and password:
29 self.user_cache = authenticate(username=username, password=password)
30 if self.user_cache is None:
31 raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive."))
32 elif not self.user_cache.is_active:
33 raise forms.ValidationError(_("This account is inactive."))
34
35 # TODO: determine whether this should move to its own method.
36 if self.request:
37 if not self.request.session.test_cookie_worked():
38 raise forms.ValidationError(_("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in."))
39
40 return self.cleaned_data
41
42 def get_user_id(self):
43 if self.user_cache:
44 return self.user_cache.id
45 return None
46
47 def get_user(self):
48 return self.user_cache
Back to Top