1

Usernames in Django are limited to max_length=30, and since Django 1.5+ they can also be set by using USERNAME_FIELD.

However, it isn't clear how the existing username field can be kept intact (with all the functionality it has) while only changing max_length. I assume some sort of monkey patching is required, but it isn't immediate what the right way to do so is.

This question is not a duplicate of existing questions that refer to versions prior to 1.5, rather it asks about a very specific monkey patch that isn't currently addressed in any other question on SO.

Yuval Adam
  • 161,610
  • 92
  • 305
  • 395
  • possible duplicate of [Can django's auth_user.username be varchar(75)? How could that be done?](http://stackoverflow.com/questions/2610088/can-djangos-auth-user-username-be-varchar75-how-could-that-be-done) – Krzysztof Szularz Aug 05 '14 at 10:18
  • @KrzysztofSzularz all of the existing questions pertain to Django pre-1.5. This specifically asks about Django 1.5+ – Yuval Adam Aug 05 '14 at 10:20
  • https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#specifying-a-custom-user-model ? – Henrik Andersson Aug 05 '14 at 10:30
  • @limelights - again, the docs do not address this very specific question of how to keep the default `username` field and only patch the max_length. – Yuval Adam Aug 05 '14 at 10:37
  • I see, what's your use-case for doing this? (Genuinely interested :) – Henrik Andersson Aug 05 '14 at 11:22
  • @limelights I'm using UUIDs as usernames, they're 36 chars long :) – Yuval Adam Aug 05 '14 at 11:27
  • 1
    Yeah, I see, I was wondering why you didn't want to/could re-implement the entire field definition instead? :) – Henrik Andersson Aug 05 '14 at 11:55
  • @limelights 1) It's impossible to override an existing field, and 2) I didn't feel like copy-pasta'ing all the existing validators, help text and translations. – Yuval Adam Aug 05 '14 at 14:58

1 Answers1

0

Currently, I have resorted to the following monkey patch which seems to work:

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import AbstractUser


class MyUser(AbstractUser):
    pass

USERNAME_LENGTH = 50
MyUser._meta.get_field('username').max_length = USERNAME_LENGTH
MyUser._meta.get_field('username').validators[0].limit_value = USERNAME_LENGTH
MyUser._meta.get_field('username').validators[1].limit_value = USERNAME_LENGTH
UserCreationForm.base_fields['username'].max_length = USERNAME_LENGTH
UserCreationForm.base_fields['username'].validators[0].limit_value = USERNAME_LENGTH
Yuval Adam
  • 161,610
  • 92
  • 305
  • 395