Introduction
Changing user models mid-project is complex. Understanding migration strategies helps avoid pitfalls.
Key Concepts
AUTH_USER_MODEL: Must be set before first migration.
Data Migration: Moving data between user models.
Real World Context
A startup that began with Django's default auth.User now needs to add a company field and use email-based login. Changing AUTH_USER_MODEL mid-project requires resetting every migration that references the user model -- a process that often takes days in production. The Profile model pattern avoids this pain entirely.
Deep Dive
Starting Fresh (Recommended)
python# 1. Create custom user model FIRST # accounts/models.py from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass # Add fields later # 2. Configure in settings.py AUTH_USER_MODEL = 'accounts.User' # 3. Then run first migration # python manage.py makemigrations # python manage.py migrate
Migrating Existing Project
python# WARNING: Complex process, consider carefully # Option 1: Database copy (if possible) # 1. Export existing user data # 2. Create new custom model # 3. Reset migrations (dangerous!) # 4. Import data # Option 2: Keep using auth.User with Profile class Profile(models.Model): user = models.OneToOneField( 'auth.User', on_delete=models.CASCADE ) # Add all extra fields here
Setting Model Early
python# Even if you don't need customization now, # create a minimal custom user model: class User(AbstractUser): class Meta: db_table = 'auth_user' # Use same table name # This makes future changes much easier
Common Pitfalls
- Changing
AUTH_USER_MODELafter the first migration: Django does not support swapping the user model after migrations have been applied. All ForeignKeys to the old model break, and data must be manually migrated. - Hardcoding
from django.contrib.auth.models import User: If you later switch to a custom model, every import breaks. Always useget_user_model()in code andsettings.AUTH_USER_MODELin models. - Forgetting to create the custom model before
migrate: Runningmigratewithout the custom model registered inAUTH_USER_MODELcreates the defaultauth_usertable, making the switch much harder.
Best Practices
- Always create custom user first: Before any migrations.
- Use Profile for existing projects: Avoid risky migrations.
- Test thoroughly: User model changes are critical.
Summary
Create custom user models before first migration. For existing projects, use Profile models. Never rush user model changes.