Restore maxlength attribute on AuthenticationForm username field

Ensure the username field widget sets the maxlength HTML attribute,
fixing a regression introduced in #27515 (5ceaf14686).
Adds tests to verify correct maxlength for default and custom user models.
This commit is contained in:
utkarsh.arya@zomato.com 2025-11-15 22:59:52 +00:00
parent b1d6b35e14
commit 4928994991
2 changed files with 31 additions and 1 deletions

View file

@ -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)

View file

@ -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):