4đź‘Ť
If your aim is to simply alter the length of the username field for the form (and not to alter the length of the username field in the database), then the correct solution is to subclass AuthenticationForm like so:
from django import forms
from django.contrib.auth.forms import AuthenticationForm
class MyAuthenticationForm(AuthenticationForm):
username = forms.CharField(label="Username", max_length=75)
In fact, the docstring for AuthenticationForm even says “Base class for authenticating users. Extend this to get a form that accepts username/password logins.”
Use your new form in place of the old AuthenticationForm in your templates, views, etc.
As for why your code isn’t working, my guess is that your app’s urls.py isn’t being loaded before the AuthenticationForm is being imported elsewhere. I couldn’t swear to that being the reason, but it’s the most likely.
0đź‘Ť
My guess: on urls.py use:
from django.contrib.auth.views import login
...
(r'^accounts/login/$', login),
instead of the “lazy evaluation” form:
(r'^accounts/login/$', 'django.contrib.auth.views.login'),
0đź‘Ť
Best way is this code added to the top level init:
# Added so the login field can take email addresses longer than 30 characters
from django.contrib.auth.forms import AuthenticationForm
AuthenticationForm.base_fields['username'].max_length = 75
AuthenticationForm.base_fields['username'].widget.attrs['maxlength'] = 75
AuthenticationForm.base_fields['username'].validators[0].limit_value = 75
However, if you choose to us @Gabriel Hurley answer above, you can pass it to the login form by using the following code:
(r'^accounts/login/$', 'django.contrib.auth.views.login', {
'authentication_form': AuthenticationForm
}),
- [Django]-Can't run Scrapy project in Django
- [Django]-Custom authentication with django?
- [Django]-Django-crispy-forms: form_class appears but label_class and field_class does not
- [Django]-Django ModelForm not validating correctly with custom date format