PageRenderTime 25ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/django/contrib/admin/forms.py

https://code.google.com/p/mango-py/
Python | 43 lines | 31 code | 6 blank | 6 comment | 10 complexity | 97ca54703215ef8ddb18750b49775b37 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. from django import forms
  2. from django.contrib.auth import authenticate
  3. from django.contrib.auth.forms import AuthenticationForm
  4. from django.contrib.auth.models import User
  5. from django.utils.translation import ugettext_lazy, ugettext as _
  6. ERROR_MESSAGE = ugettext_lazy("Please enter a correct username and password. "
  7. "Note that both fields are case-sensitive.")
  8. class AdminAuthenticationForm(AuthenticationForm):
  9. """
  10. A custom authentication form used in the admin app.
  11. """
  12. this_is_the_login_form = forms.BooleanField(widget=forms.HiddenInput, initial=1,
  13. error_messages={'required': ugettext_lazy("Please log in again, because your session has expired.")})
  14. def clean(self):
  15. username = self.cleaned_data.get('username')
  16. password = self.cleaned_data.get('password')
  17. message = ERROR_MESSAGE
  18. if username and password:
  19. self.user_cache = authenticate(username=username, password=password)
  20. if self.user_cache is None:
  21. if u'@' in username:
  22. # Mistakenly entered e-mail address instead of username? Look it up.
  23. try:
  24. user = User.objects.get(email=username)
  25. except (User.DoesNotExist, User.MultipleObjectsReturned):
  26. # Nothing to do here, moving along.
  27. pass
  28. else:
  29. if user.check_password(password):
  30. message = _("Your e-mail address is not your username."
  31. " Try '%s' instead.") % user.username
  32. raise forms.ValidationError(message)
  33. elif not self.user_cache.is_active or not self.user_cache.is_staff:
  34. raise forms.ValidationError(message)
  35. self.check_for_test_cookie()
  36. return self.cleaned_data