forms.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from django import forms
  2. from django.contrib.auth import authenticate
  3. from django.contrib.auth.forms import AuthenticationForm
  4. from django.utils.translation import ugettext_lazy, ugettext as _
  5. from django.contrib.auth import get_user_model
  6. ERROR_MESSAGE = ugettext_lazy("Please enter the correct username and password "
  7. "for a staff account. 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(
  13. widget=forms.HiddenInput, initial=1,
  14. error_messages={'required': ugettext_lazy("Please log in again, because your session has expired.")})
  15. def clean(self):
  16. username = self.cleaned_data.get('username')
  17. password = self.cleaned_data.get('password')
  18. message = ERROR_MESSAGE
  19. if username and password:
  20. self.user_cache = authenticate(
  21. username=username, password=password)
  22. if self.user_cache is None:
  23. if u'@' in username:
  24. User = get_user_model()
  25. # Mistakenly entered e-mail address instead of username? Look it up.
  26. try:
  27. user = User.objects.get(email=username)
  28. except (User.DoesNotExist, User.MultipleObjectsReturned):
  29. # Nothing to do here, moving along.
  30. pass
  31. else:
  32. if user.check_password(password):
  33. message = _("Your e-mail address is not your username."
  34. " Try '%s' instead.") % user.username
  35. raise forms.ValidationError(message)
  36. elif not self.user_cache.is_active or not self.user_cache.is_staff:
  37. raise forms.ValidationError(message)
  38. return self.cleaned_data