diff --git a/AUTHORS b/AUTHORS index e877db3fda1..3c39a273f2c 100644 --- a/AUTHORS +++ b/AUTHORS @@ -478,6 +478,7 @@ answer newbie questions, and generally made Django that much better: Loïc Bistuer Lowe Thiderman Luan Pablo + Lucas Connors Luciano Ramalho Ludvig Ericson Luis C. Berrocal diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py index a5de5bf6505..3b14a1791e3 100644 --- a/django/contrib/auth/forms.py +++ b/django/contrib/auth/forms.py @@ -155,10 +155,7 @@ class AuthenticationForm(forms.Form): Base class for authenticating users. Extend this to get a form that accepts username/password logins. """ - username = UsernameField( - max_length=254, - widget=forms.TextInput(attrs={'autofocus': True}), - ) + username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True})) password = forms.CharField( label=_("Password"), strip=False, @@ -182,8 +179,9 @@ class AuthenticationForm(forms.Form): self.user_cache = None super().__init__(*args, **kwargs) - # Set the label for the "username" field. + # Set the max length and label for the "username" field. self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD) + self.fields['username'].max_length = self.username_field.max_length or 254 if self.fields['username'].label is None: self.fields['username'].label = capfirst(self.username_field.verbose_name) diff --git a/tests/auth_tests/models/with_custom_email_field.py b/tests/auth_tests/models/with_custom_email_field.py index a98b02b8f14..27b1f810f24 100644 --- a/tests/auth_tests/models/with_custom_email_field.py +++ b/tests/auth_tests/models/with_custom_email_field.py @@ -19,5 +19,6 @@ class CustomEmailField(AbstractBaseUser): is_active = models.BooleanField(default=True) EMAIL_FIELD = 'email_address' + USERNAME_FIELD = 'username' objects = CustomEmailFieldUserManager() diff --git a/tests/auth_tests/test_forms.py b/tests/auth_tests/test_forms.py index f7d0e71ea94..f15aef37e3d 100644 --- a/tests/auth_tests/test_forms.py +++ b/tests/auth_tests/test_forms.py @@ -377,6 +377,19 @@ class AuthenticationFormTest(TestDataMixin, TestCase): self.assertTrue(form.is_valid()) self.assertEqual(form.non_field_errors(), []) + @override_settings(AUTH_USER_MODEL='auth_tests.CustomEmailField') + def test_username_field_max_length_matches_user_model(self): + self.assertEqual(CustomEmailField._meta.get_field('username').max_length, 255) + data = { + 'username': 'u' * 255, + 'password': 'pwd', + 'email': 'test@example.com', + } + CustomEmailField.objects.create_user(**data) + form = AuthenticationForm(None, data) + self.assertEqual(form.fields['username'].max_length, 255) + self.assertEqual(form.errors, {}) + @override_settings(AUTH_USER_MODEL='auth_tests.IntegerUsernameUser') def test_username_field_max_length_defaults_to_254(self): self.assertIsNone(IntegerUsernameUser._meta.get_field('username').max_length)