I'm using Django 1.9, where usernames have a 30 character limit. In order to overcome this, I created a custom user model as such:
class User(AbstractUser):
pass
# Override username max_length to allow long usernames.
User._meta.get_field('username').max_length = 255
User._meta.get_field('username').help_text = _(
'Required. 255 characters or fewer. Letters, digits and @/./+/-/_ only.')
In the shell I can create users with names longer than 30 characters, but in the admin I cannot add users with long usernames or assign long usernames to existing users. I get:
Ensure this value has at most 30 characters (it has 43).
I noticed that Django Admin's UserCreateForm and UserChangeForm have Django's default User model explicitly set in their Meta options (which shouldn't be the case, there's a ticket regarding this), so I used custom forms like this:
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
User = get_user_model()
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = User
class CustomUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = User
class CustomUserAdmin(UserAdmin):
form = CustomUserChangeForm
add_form = CustomUserCreationForm
Still it didn't work. So I added a breakpoint to the CustomUserChangeForm's init, after calling super, and I got:
ipdb> self
<UserForm bound=True, valid=False, fields=(username;password;first_name;last_name;email;is_active;is_staff;is_superuser;groups;user_permissions)>
ipdb> self._meta.model
<class 'custom.models.User'>
ipdb> self.fields['username'].max_length
255
ipdb> self.fields['username'].validators[0].limit_value
255
ipdb> self.fields['username'].clean('a_username_with_more_than_thirty_characters')
u'a_username_with_more_than_thirty_characters'
ipdb> self.errors
{'username': [u'Ensure this value has at most 30 characters (it has 38).']}
I am mind blown. I don't know what I could possibly be missing. Any ideas?