Fix InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default' in Django
This error means a migration was applied out of order, usually because a custom user model was added after Django's admin migrations already ran. Fix it by resetting the migration state: clear the django_migrations table for the conflicting app, fake-apply the dependencies in order, then run migrate again.
Reading the Stack Trace
Here's what each line means:
- File "/venv/lib/python3.11/site-packages/django/core/management/commands/migrate.py", line 334, in check_consistent_history: Django checks that all migration dependencies were applied in the correct order before running new migrations.
- File "/venv/lib/python3.11/site-packages/django/core/management/commands/migrate.py", line 97, in handle: The migrate command's main handler calls the consistency check before applying any pending migrations.
- raise InconsistentMigrationHistory(: The admin app's migration depends on your custom user model's migration, but the admin migration was applied first.
Common Causes
1. Custom user model added after initial migrate
You ran migrate before setting AUTH_USER_MODEL to a custom model, so admin.0001_initial was applied against the default User model.
# settings.py — added too late
AUTH_USER_MODEL = 'accounts.CustomUser'
# accounts/models.py
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
phone = models.CharField(max_length=20, blank=True)
2. Database copied from another project
The database was cloned from a different project that had different migration history, causing dependency mismatches.
# Copied production DB to local dev
$ pg_dump prod_db | psql local_db
$ python manage.py migrate
# Fails because local code has different migration graph
3. Squashed migrations with broken dependency chain
After squashing migrations, the dependency references were not updated to point to the squashed migration.
# accounts/migrations/0001_squashed_0005.py
class Migration(migrations.Migration):
replaces = [
('accounts', '0001_initial'),
('accounts', '0002_add_phone'),
]
dependencies = [] # Missing dependency on auth.0001_initial
The Fix
The cleanest fix in development is to drop the database and re-run migrations with the custom user model configured from the start. In production, you must carefully clear the conflicting rows from the django_migrations table and fake-apply them in the correct order.
# settings.py — AUTH_USER_MODEL was set after running migrate
AUTH_USER_MODEL = 'accounts.CustomUser'
# Running: python manage.py migrate
# Raises InconsistentMigrationHistory
# 1. Drop and recreate the database (development only)
$ dropdb myproject_db && createdb myproject_db
# 2. Ensure AUTH_USER_MODEL is set BEFORE first migrate
# settings.py
AUTH_USER_MODEL = 'accounts.CustomUser'
# 3. Run migrations fresh
$ python manage.py migrate
Testing the Fix
import pytest
from django.core.management import call_command
from django.test import TestCase
class TestMigrations(TestCase):
def test_migrations_are_consistent(self):
"""Ensure no migration conflicts exist."""
try:
call_command('migrate', '--check', verbosity=0)
except SystemExit as e:
if e.code != 0:
pytest.fail('Unapplied migrations detected')
def test_no_missing_migrations(self):
"""Ensure all model changes have migrations."""
try:
call_command('makemigrations', '--check', '--dry-run', verbosity=0)
except SystemExit as e:
if e.code != 0:
pytest.fail('Model changes without migrations detected')
Run your tests:
pytest
Pushing Through CI/CD
git checkout -b fix/django-migration-inconsistency,git add accounts/migrations/ settings.py,git commit -m "fix: resolve migration dependency ordering for custom user model",git push origin fix/django-migration-inconsistency
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:15
env:
POSTGRES_DB: test_db
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
ports:
- 5432:5432
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.11'
cache: 'pip'
- run: pip install -r requirements.txt
- run: python manage.py migrate --check
- run: pytest --tb=short -q
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
pip install bugstack
Step 2: Initialize
import bugstack
bugstack.init(api_key=os.environ["BUGSTACK_API_KEY"])
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run the full test suite locally to confirm migrations apply cleanly.
- Open a pull request with the migration fix.
- Wait for CI checks including the migrate --check step to pass.
- Have a teammate review and approve the PR.
- Merge to main and verify the deployment in staging before promoting to production.
Frequently Asked Questions
BugStack runs the fix through your existing test suite, generates additional edge-case tests, and validates that migrations apply cleanly on a fresh database before marking it safe to deploy.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
Yes. Delete the conflicting rows from the django_migrations table, then use python manage.py migrate --fake to re-record them in the correct order. This is necessary in production environments.
Always set AUTH_USER_MODEL before running your first migration. Add a CI step that runs migrate --check on a fresh database to catch ordering issues early.