[Django]-Django admin login form – overriding max_length failing

8👍

It looks like I need to modify the widget attrs directly.

I forgot that fields are instantiated once!
CharField(max_length=30) is already setting the widget attributes for the HTML. No matter how I change max_length on a field instance, the widget has already been generated.

Here’s my solution in my monkey_patch app.

from django.contrib.auth.forms import AuthenticationForm

AuthenticationForm.base_fields['username'].max_length = 150 # I guess not needed
AuthenticationForm.base_fields['username'].widget.attrs['maxlength'] = 150 # html
AuthenticationForm.base_fields['username'].validators[0].limit_value = 150

I don’t really understand why instantiating a new field instance doesn’t work..?

AuthenticationForm.base_fields['username'] = forms.CharField(max_length=100) 

3👍

In django 1.3 you can build an app with the following code and make sure you include it in the settings. Its a very similar solution to the accepted one but it extends from AdminAuthenticationForm, otherwise your non-field errors won’t get displayed.

from django.contrib.admin.forms import AdminAuthenticationForm
from django import forms
from django.contrib.admin.sites import AdminSite

class LongerAuthenticationForm(AdminAuthenticationForm):
    """ Subclass which extends the max length of the username field. """
    username = forms.CharField(max_length=150)


AdminSite.login_form = LongerAuthenticationForm

1👍

from django.contrib.admin.forms import AdminAuthenticationForm

class ModifiedForm(AdminAuthenticationForm):
    username = forms.CharField(max_length=150) #and so on

into urls.py

from django.contrib import admin
admin.site.login_form = ModifiedForm

...

admin.autodiscover()

Leave a comment