Search code examples
pythondjangoinheritancemigrationmaxlength

How to override max length of username in Django by creating a custom model


I have a problem. I'm using Django 1.7, and have already made a custom user model, that inherits Django's abstract user like this:

class CustomUser(AbstractUser, BaseModel):

Now they say in here Django-ticket, that I could avoid the problem of username's max_length being 30, by creating a custom user. Well, I already have a custom user, so it should be easy right? How I tried to do it was:

class CustomUser(AbstractUser, BaseModel):

      username = models.CharField(max_length=70, unique=True, db_index=True)

Now when I try to make migrations for changing this field, it results in an error: django.core.exceptions.FieldError: Local field 'username' in class 'CustomUser' clashes with field of similar name from base class 'AbstractUser'

What am I doing wrong? How could I solve this problem? I have data that should be migrated, so I cannot empty database.


Solution

  • If you want it to be more flexible inherit from AbstractBaseUser instead, you will be able to specify your own username field that way, e.g.

    class User(AbstractBaseUser):
        email = models.EmailField(
            verbose_name='email address',
            max_length=255,
            unique=True,
        )
    
        is_active = models.BooleanField(default=True)
        is_admin = models.BooleanField(default=False)
    
        date_joined = models.DateTimeField(
            verbose_name=_('date created'),
            auto_created=True,
            default=timezone.now
        )
    
        objects = UserManager()
    
        USERNAME_FIELD = 'email'
        REQUIRED_FIELDS = []
    

    https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#specifying-a-custom-user-model