Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
django 2.1.7

Create a custom user model to use as the new default

Gotcha! Django comes with a default auth library that utilizes a default hidden User model. This default model cannot be easily migrated so DO NOT use this model. Even the Django docs recommend extending this into a custom user model.

Why would you want to extend the model? Imagine you later want to record a users birthdate, using the default model, there is no easy way to add this field to the model. By extending the mode you are future proofing your user model.

Gotcha! Extending the model won’t be enough. In creating your own User model, you must...

  • Step 1: Create new app with "manage.py startapp"
    $ python manage.py startapp users
  • Step 2: Create a new user model that extends the default User model (docs)

This is the simplest version, suggested by the docs.

Note that its super hard to use a custom user model after you run migrate

DO NOT run migrate until this model is created AND the user is overriden in settings.

Lets also create the CustomUserManager in the same step, since we will use it in the future.

    # user/models.py
    from django.contrib.auth.models import AbstractUser, UserManager
    
    class CustomUserManager(UserManager):
        pass
    
    class User(AbstractUser):
        objects = CustomUserManager()
  • Step 3: Update settings
  1. Add "users" to the list of installed apps
  2. Override the default "Auth User Model" in settings
    # settings.py

    INSTALLED_APPS = [
        # ...
        'users'
    ]
    # ...
    AUTH_USER_MODEL = 'users.User' # from the app “users”
  • Step 4: Update the connected User forms

According to the docs, if you want a Custom User model, two forms must be rewritten or extended: UserCreationForm and UserChangeForm. This example is the no-op version of extending these forms.

    # users/forms.py
    from django.contrib.auth import get_user_model
    from django.contrib.auth.forms import UserChangeForm, UserCreationForm
    
    User = get_user_model()
    
    class UserChangeForm(UserChangeForm):
    
        class Meta(UserChangeForm.Meta):
            model = User
    
    
    class UserCreationForm(UserCreationForm):
    
        class Meta(UserCreationForm.Meta):
            model = User
  • Step 5: Make migrations and migrate

Now it is safe to run your first migrate command.

    $ python manage.py makemigrations users
    $ python manage.py migrate 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.