Hello site
[auf_framonde.git] / eggs / Django-1.4.5-py2.7.egg / django / contrib / admin / forms.py
1 from django import forms
2
3 from django.contrib.auth import authenticate
4 from django.contrib.auth.forms import AuthenticationForm
5 from django.contrib.auth.models import User
6
7 from django.utils.translation import ugettext_lazy, ugettext as _
8
9 ERROR_MESSAGE = ugettext_lazy("Please enter the correct username and password "
10 "for a staff account. Note that both fields are case-sensitive.")
11
12 class AdminAuthenticationForm(AuthenticationForm):
13 """
14 A custom authentication form used in the admin app.
15
16 """
17 this_is_the_login_form = forms.BooleanField(widget=forms.HiddenInput, initial=1,
18 error_messages={'required': ugettext_lazy("Please log in again, because your session has expired.")})
19
20 def clean(self):
21 username = self.cleaned_data.get('username')
22 password = self.cleaned_data.get('password')
23 message = ERROR_MESSAGE
24
25 if username and password:
26 self.user_cache = authenticate(username=username, password=password)
27 if self.user_cache is None:
28 if u'@' in username:
29 # Mistakenly entered e-mail address instead of username? Look it up.
30 try:
31 user = User.objects.get(email=username)
32 except (User.DoesNotExist, User.MultipleObjectsReturned):
33 # Nothing to do here, moving along.
34 pass
35 else:
36 if user.check_password(password):
37 message = _("Your e-mail address is not your username."
38 " Try '%s' instead.") % user.username
39 raise forms.ValidationError(message)
40 elif not self.user_cache.is_active or not self.user_cache.is_staff:
41 raise forms.ValidationError(message)
42 self.check_for_test_cookie()
43 return self.cleaned_data