Skip to main content

django-migration-auditor

CI PyPI Python Django License: MIT

A Django package that logs every migration run with schema diffs, timestamps, executor identity, and generates rollback scripts automatically.


✨ Features

Feature Description
Full Audit Trail Records every apply / unapply with app, migration name, direction, who ran it, environment, hostname, database alias, start/end timestamps, and duration.
Schema Diffs Captures before/after schema snapshots via connection.introspection and stores a human-readable diff (tables, columns, indexes, constraints).
Auto Rollback Scripts Generates .sql rollback scripts for each applied migration using SchemaEditor(collect_sql=True) — no subprocess, no side effects.
Management Commands audit_migrations (list/filter/export), generate_rollback (on-demand SQL), migration_report (summary stats).
Django Admin Read-only admin panel with colour-coded badges, collapsible schema diffs, date hierarchy, and full-text search.
Zero Config Works out of the box — just add to INSTALLED_APPS and run migrate.
Fail-Safe Audit failures never break real migrations. All recording is wrapped in try/except.

📦 Installation

pip install django-migration-auditor

Or for development:

git clone https://github.com/abburisaikarthik/django-migration-auditor.git
cd django-migration-auditor
pip install -e ".[dev]"

🚀 Quick Start

1. Add to INSTALLED_APPS

# settings.py
INSTALLED_APPS = [
    # ...
    "migration_auditor",
]

2. Run migrations

python manage.py migrate

This creates the migration_auditor_log table and starts auditing immediately.

3. View audit logs

# Table format (default)
python manage.py audit_migrations

# JSON
python manage.py audit_migrations --format json

# CSV
python manage.py audit_migrations --format csv

# Filter by app and status
python manage.py audit_migrations --app myapp --status failed --since 2024-01-01

4. View summary report

python manage.py migration_report
python manage.py migration_report --app myapp

5. Generate rollback scripts

# Save to file
python manage.py generate_rollback --app myapp --name 0002_add_field

# Print to stdout
python manage.py generate_rollback --app myapp --name 0002_add_field --stdout

6. Django Admin

Navigate to /admin/migration_auditor/migrationauditlog/ for a read-only view of all audit entries with:

  • Colour-coded direction badges (▲ Apply / ▼ Unapply)
  • Status badges (Success / Failed / In Progress)
  • Collapsible schema diff and rollback SQL sections
  • Date hierarchy, filters, and search

⚙️ Configuration

All settings are optional. Configure via the MIGRATION_AUDITOR dict in settings.py:

MIGRATION_AUDITOR = {
    # Master switch — set to False to disable all auditing.
    "ENABLED": True,

    # Directory for .sql rollback files (relative to BASE_DIR or absolute).
    "ROLLBACK_DIR": "rollbacks",

    # Capture before/after schema snapshots.
    "CAPTURE_SCHEMA_DIFF": True,

    # Optional callable: (request) -> str to resolve the current user.
    # Only useful with the optional middleware.
    "USER_RESOLVER": None,

    # Override automatic environment detection.
    # When None, checks DJANGO_ENV → ENVIRONMENT → DJANGO_SETTINGS_MODULE.
    "ENVIRONMENT": None,

    # App labels to skip (never audit these).
    "EXCLUDE_APPS": [],

    # Max chars for schema diff storage.  0 = unlimited.
    "MAX_DIFF_LENGTH": 0,
}

Environment Detection

The package auto-detects the environment by checking (in order):

  1. MIGRATION_AUDITOR["ENVIRONMENT"] setting
  2. DJANGO_ENV environment variable
  3. ENVIRONMENT environment variable
  4. Keywords in DJANGO_SETTINGS_MODULE (prod, staging, dev, test, local)
  5. Falls back to "unknown"

User Detection

The executor identity is resolved by checking (in order):

  1. Custom USER_RESOLVER callable (if middleware is installed)
  2. MIGRATION_AUDITOR_USER environment variable
  3. USER / USERNAME / LOGNAME environment variables
  4. getpass.getuser() (OS-level username)

🔌 Optional Middleware

If you need to identify the Django user who triggered a migration (e.g. from a custom admin view), add the middleware:

MIDDLEWARE = [
    # ...
    "migration_auditor.middleware.MigrationAuditorMiddleware",
]

Then configure a USER_RESOLVER:

MIGRATION_AUDITOR = {
    "USER_RESOLVER": lambda request: str(request.user) if request.user.is_authenticated else "anonymous",
}

Note: This is only useful in rare setups where migrations run inside a request cycle. For normal manage.py migrate usage, the middleware is not needed.


📊 Audit Record Fields

Field Type Description
app_label CharField Django app label
migration_name CharField Migration file name
direction CharField apply or unapply
applied_by CharField Who ran the migration
environment CharField Runtime environment
hostname CharField Machine hostname
database_alias CharField Django DB alias
started_at DateTimeField When it began
finished_at DateTimeField When it finished
duration_ms IntegerField Wall-clock time (ms)
status CharField success, failed, or in_progress
error_detail TextField Full traceback on failure
schema_diff TextField Human-readable schema diff
rollback_sql TextField SQL to reverse the migration
rollback_script_path CharField Path to saved .sql file

🧪 Running Tests

pip install -e ".[dev]"
pytest tests/ -v

📋 How It Works

  1. Signal Interception: On pre_migrate, the package monkey-patches MigrationExecutor with AuditingMigrationExecutor.
  2. Schema Snapshot: Before each migration, a snapshot of the database schema is taken via connection.introspection.
  3. Migration Execution: The original apply_migration() / unapply_migration() runs normally.
  4. Post-Execution:
    • A second schema snapshot is taken and diffed against the first.
    • Rollback SQL is generated via SchemaEditor(collect_sql=True) — dry-run, nothing is executed.
    • The rollback SQL is saved to a .sql file.
    • A MigrationAuditLog row is written with all metadata.
  5. Fail-Safe: All audit operations are wrapped in try/except. If anything goes wrong with recording, the real migration still completes.

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Run tests (pytest tests/ -v)
  4. Commit changes (git commit -m 'Add amazing feature')
  5. Push to branch (git push origin feature/amazing-feature)
  6. Open a Pull Request

📄 License

This project is licensed under the MIT License — see the LICENSE file for details.

Metadata

Release files for django-migration-auditor 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-migration-auditor 0.1.0
File Size Uploaded Provenance Actions
django_migration_auditor-0.1.0.tar.gz 23.4 kB Without provenance Details for django_migration_auditor-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-migration-auditor 0.1.0
File Interpreter ABI Platform Actions
django_migration_auditor-0.1.0-py3-none-any.whl Python 3 none any Details for django_migration_auditor-0.1.0-py3-none-any.whl

Total release size: 48.1 kB

Release files / django_migration_auditor-0.1.0.tar.gz

Download URL django_migration_auditor-0.1.0.tar.gz
Size 23.4 kB
Tags Source
SHA-256 checksum
How to use checksums
33e57040789dc9270e0a4ad0b3b96fed4eb8a02d72a9970f4ea4d813b75674a6
BLAKE2b-256 checksum
How to use checksums
7eb5fd19762fac9ddd54840cf45366af7ac24b127e26334ad0bdcf26f7c77f50
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.8

Release files / django_migration_auditor-0.1.0-py3-none-any.whl

Download URL django_migration_auditor-0.1.0-py3-none-any.whl
Size 24.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
341a06b2dcbc41b59bd2db8d1c1bf555044b7003ece55b663cf5a10e5b988fc0
BLAKE2b-256 checksum
How to use checksums
dd4ce54d5ad2f243f1dd54192a40a42315e3e5194bbc651d4601e12d9dbe7670
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.8

Security for django-migration-auditor 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page