In Django 2.0.13, the django.contrib.auth.AuthenticationForm
renders with the username
field like the below markup:
<label class="required" for="id_username">Username:</label> <input type="text" name="username" autofocus maxlength="254" required id="id_username" />
Notice the maxlength="254"
attribute is present.
In Django 2.1.12, the maxlength
attribute is no longer rendered on the username
field markup:
<label class="required" for="id_username">Username:</label> <input type="text" name="username" autofocus required id="id_username">
We have a use case where we extend the AuthenticationForm
to limit the user to input of length 6, since our users have a few different ways they use to login to various other applications (company email addresses, 6 character user logins, etc.), and inadvertently create multiple users in our Django application. We limit the username
field to 6 characters so if a user starts to enter their email address, they would hit the HTML maxlength
and realize they are using the wrong identifier to login to our application.
How we are doing this now (Django 2.0.13) is overriding the username
attribute of the class, basically copying the attribute definition from AuthenticationForm
:
class CustomAuthenticationForm(AuthenticationForm):
username = UsernameField(
max_length=6,
widget=forms.TextInput(attrs={'autofocus': True}),
)
This works fine and we get markup like below, with maxlength="6"
attribute:
<label class="required" for="id_username">Username:</label> <input type="text" name="username" autofocus maxlength="6" required id="id_username" />
In Django 2.1, max_length
is no longer set on the defenition of the username
attribute, but in __init__
. If we keep the same code as above, we get the same markup, but the UsernameField.max_length
is overriden to 150 from the User
model. So we’re in a state where the UsernameField.max_length
is 150, but the widget’s TextInput.attrs['maxlength']
is ‘6’ and the MaxLengthValidator.limit_value
is 6.
Was removing the HTML validation in Django 2.1 intentional? When overriding the AuthenticationForm
should we also be overriding __init__
to set the UsernameField.max_length
back to 6 so it matches all of the other max length-related values on the form? If removing the HTML validation from Django 2.1 out of the box was intentional, I’d like to get some recommendations on the best way to extend this class so we don’t cause any problems for ourselves or lose any features from the AuthenticationForm
when we do Django upgrades in the future.
Thanks!
Edit:
Would something like this work?: https://github.com/gopackgo90/django/commit/dd9be672ec079e90b8dfa4a8e91f31ec8185438f
This would create the right HTML attribute and validator from the UserModel. I haven’t checked on what side effect this would have on other places that use UsernameField
or checked any tests, but if someone thinks this is worth pursuing I can make a DjangoProject Issue or whatever the first steps are.