Skip to content

Debugging Django in production without DEBUG=True

Reproduce and diagnose Django bugs in production safely — without DEBUG=True — using structured logs, Sentry traces, shell_plus, query inspection, and SQL EXPLAIN.

A Django bug only reproduces in production. The temptation is to flip DEBUG=True for ten minutes and read the yellow traceback page in the browser. Don’t — that page leaks SECRET_KEY, environment variables, settings, and the full DB schema to anyone who triggers an error. This runbook collects the tools that let you diagnose the same bug without exposing the internals: structured logs, Sentry breadcrumbs, manage.py shell_plus, query inspection, and EXPLAIN ANALYZE against the actual production data.

How to verify

Confirm DEBUG is off and structured logging is reaching the journal:

python manage.py shell -c "from django.conf import settings; print('DEBUG=', settings.DEBUG)"
python manage.py check --deploy
journalctl -u gunicorn-app -n 50 --no-pager | grep -E "ERROR|WARN"
python manage.py diffsettings | grep -E "DEBUG|ALLOWED_HOSTS|SENTRY"
grep -c "django.request" /var/log/syslog 2>/dev/null

If DEBUG is True in production, stop reading and fix that first — every subsequent debugging tip assumes it’s False.

What’s happening

DEBUG=True does three dangerous things at once. First, the 500 error page renders the full traceback with locals — including session keys, DB credentials parsed into kwargs, and any object in scope. Second, django.db keeps every SQL query in memory for the request lifetime, which leaks memory under load. Third, ALLOWED_HOSTS is bypassed, so a Host-header injection gives an attacker the debug page from any DNS name pointing at your server. The right model is: production stays DEBUG=False always, and you diagnose through tools that don’t expose internals.

The substitute is layered. Sentry (or a similar APM) catches exceptions with breadcrumbs — log lines, ORM queries, HTTP calls leading up to the error — and shows them on a private dashboard. django.request and django.db.backends loggers can emit structured JSON to journald, queryable with journalctl --output=json. manage.py shell_plus --print-sql lets a senior engineer run a query under the same Django ORM and settings as production, against a read-replica, without rendering anything to a browser. And EXPLAIN ANALYZE against PostgreSQL is still the truth for “why is this slow.”

The procedure

  1. Verify settings.py is locked down:

    import os
    DEBUG = os.environ.get("DJANGO_DEBUG") == "True"  # default False
    ALLOWED_HOSTS = [h.strip() for h in os.environ["ALLOWED_HOSTS"].split(",")]
    SECURE_SSL_REDIRECT = True
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True

    Run python manage.py check --deploy — it flags missing security middleware, DEBUG=True, and a wildcard ALLOWED_HOSTS.

  2. Wire Sentry with breadcrumbs for ORM and HTTP:

    import sentry_sdk
    from sentry_sdk.integrations.django import DjangoIntegration
    
    sentry_sdk.init(
        dsn=os.environ["SENTRY_DSN"],
        integrations=[DjangoIntegration()],
        traces_sample_rate=0.05,        # 5% of requests get full trace
        send_default_pii=False,         # never send user IPs / cookies
        environment=os.environ.get("ENV", "prod"),
        release=os.environ.get("GIT_SHA"),
    )

    Set SENTRY_DSN only in production, not staging — staging error rates inflate your free tier.

  3. Configure structured logging for django.request and django.db.backends:

    LOGGING = {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "json": {
                "()": "pythonjsonlogger.jsonlogger.JsonFormatter",
                "format": "%(asctime)s %(name)s %(levelname)s %(message)s",
            },
        },
        "handlers": {
            "stdout": {"class": "logging.StreamHandler", "formatter": "json"},
        },
        "loggers": {
            "django.request": {"handlers": ["stdout"], "level": "WARNING"},
            "django.db.backends": {"handlers": ["stdout"], "level": "WARNING"},
            "django.security": {"handlers": ["stdout"], "level": "WARNING"},
        },
    }

    Don’t set django.db.backends to DEBUG in production — it logs every SQL statement, including parameter values, which often contain PII.

  4. To inspect a specific request that errored, open the Sentry event and copy the request URL, method, and user. Then on a production read-replica host:

    python manage.py shell_plus --print-sql
    >>> from django.test.utils import CaptureQueriesContext
    >>> from django.db import connection
    >>> with CaptureQueriesContext(connection) as ctx:
    ...     result = Order.objects.filter(customer_id=123).select_related('customer')
    ...     list(result)
    >>> for q in ctx.captured_queries:
    ...     print(q['sql'][:200], q['time'])
  5. For a slow query Sentry flagged, paste the SQL into psql against the read-replica and prefix with EXPLAIN (ANALYZE, BUFFERS):

    EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
    SELECT * FROM orders WHERE customer_id = 123;

    Look for sequential scans on large tables, planned vs actual row mismatches over 10x, and unindexed sort steps.

  6. Toggle debug for one request by IP using django-debug-toolbar with an IP whitelist — only an internal INTERNAL_IPS range sees the toolbar, the rest of the internet sees normal pages:

    INTERNAL_IPS = ["10.0.0.0/8"]   # bastion or VPN range only
    INSTALLED_APPS += ["debug_toolbar"]
    MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"]

    This still requires DEBUG=True for the toolbar’s panels to render — only use this technique on a staging replica of production, never on prod itself.

Common pitfalls

  • Leaving DEBUG=True “for five minutes” — error pages get cached by Cloudflare or a CDN, and the leak persists after you flip it back. Never flip on production.
  • Logging at DEBUG level for django.db.backends — query parameters appear in logs, including hashed passwords and credit card last-4s. Audit-failing.
  • Sentry breadcrumbs containing user input — set send_default_pii=False and before_send filters that strip request bodies.
  • manage.py shell against the primary DB during a P1 — a curious Order.objects.all() materializes 50M rows and OOMs the host. Always read from a replica, paginate aggressively.
  • EXPLAIN ANALYZE runs the query — for a write or a DELETE, wrap in BEGIN; ... ROLLBACK;. Otherwise you’ve executed it.

For tightening the same model on a Channels/ASGI deployment, see Deploying Django Channels for WebSocket production traffic. Stack Harbor’s managed operations practice runs DEBUG=False always, ships every Django exception to Sentry with PII filters, and gives the on-call team a read-replica shell_plus shortcut so production diagnostics never require flipping the debug switch.