diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py index a0cfed0995..85d4926b02 100644 --- a/django/contrib/auth/forms.py +++ b/django/contrib/auth/forms.py @@ -191,7 +191,10 @@ class AuthenticationForm(forms.Form): # 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 + username_max_length = self.username_field.max_length or 254 + self.fields['username'].max_length = username_max_length + # Update the widget's maxlength HTML attribute to match the field's max_length + self.fields['username'].widget.attrs['maxlength'] = str(username_max_length) if self.fields['username'].label is None: self.fields['username'].label = capfirst(self.username_field.verbose_name) diff --git a/tests/auth_tests/test_forms.py b/tests/auth_tests/test_forms.py index 7085dcfa11..bae91b4c25 100644 --- a/tests/auth_tests/test_forms.py +++ b/tests/auth_tests/test_forms.py @@ -513,6 +513,33 @@ class AuthenticationFormTest(TestDataMixin, TestCase): with self.subTest(field_name=field_name, autocomplete=autocomplete): self.assertEqual(form.fields[field_name].widget.attrs['autocomplete'], autocomplete) + def test_username_field_maxlength_in_widget(self): + """ + The username field's maxlength attribute should be set in the widget. + """ + form = AuthenticationForm() + # Check that the field has max_length set + self.assertEqual(form.fields['username'].max_length, 150) + # Check that the widget has maxlength attribute + self.assertEqual(form.fields['username'].widget.attrs.get('maxlength'), '150') + # Check that it renders in the HTML + rendered = str(form['username']) + self.assertIn('maxlength="150"', rendered) + + @override_settings(AUTH_USER_MODEL='auth_tests.CustomEmailField') + def test_username_field_maxlength_in_widget_for_custom_user(self): + """ + The username field's maxlength attribute should match custom user model. + """ + form = AuthenticationForm() + # CustomEmailField has username with max_length=255 + self.assertEqual(form.fields['username'].max_length, 255) + # Check that the widget has maxlength attribute + self.assertEqual(form.fields['username'].widget.attrs.get('maxlength'), '255') + # Check that it renders in the HTML + rendered = str(form['username']) + self.assertIn('maxlength="255"', rendered) + class SetPasswordFormTest(TestDataMixin, TestCase):