Fix Issues
Troubleshooting playbooks for Django production failures, from 500 errors to broken uploads.
Best for developers who already deployed and now need to restore service fast.
Fix guides start from a symptom you can see: an error message, a status code, or a behaviour such as users being logged out. Each one narrows the problem to a layer, finds the cause in the logs, and applies the smallest fix that works.
Search for the exact error text if you have it. Otherwise browse by topic: the common production failures, such as 502s, CSRF errors, and missing static files, each have their own guide.
Topics in Fix Issues
Grouped by guide type, then difficulty
Narrow the list by experience level or stack, then work through the matching guides in recommended order.
Troubleshooting guides
Use focused recovery playbooks to diagnose and fix common production failures fast.
A DisallowedHost error in Django production means Django rejected the incoming Host header. This is a security check, not a random app failure.
A common production failure is that your Django app loads, but CSS, JavaScript, or Django admin assets are missing.
CSRF Verification Failed in Django production usually appears after a deployment change that affects domains, HTTPS, cookies, or proxy headers.
Fix Django media files returning 404 or 403 in production: MEDIA_URL and MEDIA_ROOT, the static() helper, Nginx alias rules, permissions, and object storage.
Find the real cause of a Django 500 error in production: where tracebacks go with DEBUG off, logging setup, common causes, safe reproduction, and verification.
Fix Django apps that break when DEBUG is turned off: ALLOWED_HOSTS, static files, manifest errors, error templates, email handlers, and hidden exceptions.
Fix 403 Forbidden for Django static and media files served by Nginx: directory traversal permissions, file modes, alias paths, SELinux contexts, and verification.
Fix an unstyled Django admin in production: collectstatic, STATIC_URL and alias paths, WhiteNoise order, MIME types, subpath deployments, CSP, and mixed content.
Fix the SECRET_KEY must not be empty error in production: find where settings load, pass the key to systemd, Docker, CI, and cron, and avoid unsafe defaults.
Fix ModuleNotFoundError when Gunicorn starts Django: wrong virtualenv, working directory, project module path, missing packages, and Python version mismatches.
Fix Gunicorn errors that cannot find the Django application object: wrong module or attribute names, shadowed modules, ASGI paths, and wsgi.py mistakes.
Fix Gunicorn Connection in use and Address already in use errors: find the process holding the port or socket, stop duplicate services, and prevent stale sockets.
Fix PermissionError when Django saves uploads: service user ownership, MEDIA_ROOT location, upload file modes, systemd sandboxing, Docker volumes, and SELinux.
Fix psycopg and psycopg2 install failures on servers and Docker images: pg_config not found, missing libpq, binary versus source builds, and missing wheels.
Diagnose Django emails that never arrive: backend settings, fail_silently, blocked SMTP ports, provider rejections, Celery tasks, and domain authentication.
Fix Django connection errors to PostgreSQL in Docker Compose: localhost versus service names, readiness health checks, credentials in volumes, networks, and ports.
Fix deploys that seem to do nothing: Gunicorn not reloaded, old processes still running, wrong release directory, cached templates, and stale assets.
Fix SQLite database is locked errors in Django: concurrent writes, long transactions, WAL mode, timeouts, IMMEDIATE transactions, and when to migrate.
Fix ValueError: Missing staticfiles manifest entry in Django production: collectstatic not run, wrong STATIC_ROOT, typos in static paths, missing apps, and build-time settings mismatches.
Fix Gunicorn HaltServer 'Worker failed to boot' for Django: find the real traceback, reproduce the import with the same environment, and fix settings, imports, and startup-time side effects.
Fix ProgrammingError: relation does not exist (and SQLite 'no such table') in Django production: unapplied or uncommitted migrations, the wrong database, faked migrations, and import-time queries.
Fix FATAL: password authentication failed for user in Django: read the server-side reason, URL-encode special characters, reload environment variables, fix Docker volume passwords, and pg_hba methods.
Fix Django settings missing environment variables under Docker Compose: .env versus env_file, variable precedence, recreating containers, $ in values, build-time versus runtime, and docker compose config.
Fix the Welcome to nginx page appearing instead of your Django site: enable the site, remove the default server, match server_name, add the HTTPS and IPv6 listeners, and reload after nginx -t.
Fix Django settings that miss variables from a systemd EnvironmentFile: file syntax rules, the '-' prefix, quoting, no variable expansion, daemon-reload versus restart, and checking a running process.
Fix mixed content on a Django site served over HTTPS: find http:// resources, correct absolute URLs behind a proxy, fix storage and CDN URLs, rewrite stored content, and add upgrade-insecure-requests.
Fix Celery workers that log Cannot connect to amqp://guest@127.0.0.1:5672 when you configured Redis: load Django settings in celery.py, use the CELERY_ namespace correctly, and pass the broker URL to every process.
Fix password reset emails, sitemaps, and allauth links that point to example.com: update the Site record, set SITE_ID, handle multiple environments, and get https in generated links.
Fix TemplateDoesNotExist that appears only in production: case-sensitive paths, TEMPLATES DIRS relative to the wrong directory, apps missing from INSTALLED_APPS, files excluded from images, and cached loaders.
Fix Refused to apply style and Expected a JavaScript module script errors for Django static files: HTML 404 pages served as CSS, missing mime.types in Nginx, .mjs and .wasm types, and WhiteNoise.
Fix Django media uploads that vanish after a redeploy: ephemeral container and PaaS filesystems, MEDIA_ROOT inside release directories, missing volumes, and moving uploads to object storage.
Fix the Nginx warning conflicting server name example.com on 0.0.0.0:80, ignored: find duplicate server blocks in sites-enabled and conf.d, remove leftover Certbot or default configs, and make the right Django site answer.
Fix nginx [emerg] errors that stop Nginx from starting or reloading for a Django site: unknown directive, directive is not allowed here, host not found in upstream, cannot load certificate, and unexpected end of file.
Fix nginx bind() to 0.0.0.0:80 failed (98: Address already in use) on a Django server: find the process holding port 80 or 443, stop Apache or a stray Nginx, and fix duplicate listen directives and Docker port clashes.
Fix an Nginx 404 Not Found page for Django URLs that work with runserver: route requests to Gunicorn instead of the filesystem, fix try_files and location ordering, root versus alias, and trailing-slash mismatches.
Fix a Django site where HTTPS does not load after installing a certificate: open port 443 in the firewall and cloud security group, add a listen 443 ssl block, check DNS and the certificate, and make Django aware of HTTPS.
Fix NET::ERR_CERT_COMMON_NAME_INVALID and certificate name mismatch errors on a Django site: issue one certificate for both www and the apex domain, redirect to a canonical host, and check DNS, SNI, and default server blocks.
Fix Certbot Challenge failed for domain errors when getting a first Let's Encrypt certificate for Django: unauthorized 404 on the ACME path, DNS problems, closed port 80, Cloudflare proxying, and redirects that break HTTP-01.
Fix the Django RuntimeWarning DateTimeField received a naive datetime while time zone support is active: use timezone.now, make parsed and imported datetimes aware, and set USE_TZ, TIME_ZONE, and database time zones correctly.
Fix Django errors FATAL role does not exist and FATAL database does not exist when connecting to PostgreSQL: create the role and database, match the names in settings, and avoid connecting as the Linux user by accident.
Fix Django FATAL Peer authentication failed for user when connecting to local PostgreSQL: understand peer versus password auth in pg_hba.conf, connect over TCP with HOST=localhost, or map the Linux user correctly.
Fix Django OperationalError 1045 Access denied for user when connecting to MySQL or MariaDB: match the user host part, use TCP instead of the socket, fix authentication plugins, and grant privileges on the right database.
Fix pip install mysqlclient failures for Django: mysql_config not found, pkg-config cannot find mysqlclient, and missing Python.h, on Ubuntu, Debian, RHEL, Alpine, macOS, and in Docker builds.
Stop Django failing with could not connect to server or connection refused when Docker Compose starts it before PostgreSQL is ready: use depends_on with service_healthy, pg_isready health checks, and retry logic in the entrypoint.
Fix Django containers that fail with exec ./entrypoint.sh: permission denied or exec format error and no such file or directory: set the executable bit in Git, convert CRLF line endings, and use the right shebang.
Stop Docker container logs from filling the disk on a Django server: find the large json.log files, set max-size and max-file in daemon.json or Compose, use the local driver, and reduce noisy logging.
Fix Gunicorn Connection in use or Permission denied when binding to port 80 or 443: bind Gunicorn to a high port or Unix socket behind Nginx, or grant CAP_NET_BIND_SERVICE safely instead of running as root.
Understand and silence the Uvicorn message ASGI lifespan protocol appears unsupported when serving Django: why Django does not handle lifespan events, how to turn lifespan off, and where to put startup code instead.
Fix Django logging that shows nothing in production: why logger.info disappears with DEBUG off, configure LOGGING with console handlers, find Gunicorn and systemd output in journalctl, and capture errors from Celery.
Fix Django management commands that work in your shell but fail or do nothing in cron: use the virtualenv Python with full paths, load environment variables and settings, set the working directory, and capture output and errors.
Fix pip error externally-managed-environment on Ubuntu 24.04, Debian 12, and other PEP 668 systems when installing Django: create a virtualenv or use uv, use pipx for tools, and avoid --break-system-packages on servers.
Fix Heroku H10 App crashed errors for Django apps: read the crash in heroku logs, fix the Procfile and gunicorn command, bind to $PORT, set config vars like SECRET_KEY and DATABASE_URL, and handle release-phase failures.
Fix Django deploys failing on Render, Railway, Fly.io, Cloud Run, and App Runner with no open ports detected, failed to bind to PORT, or application failed to respond: bind Gunicorn to 0.0.0.0 and the platform's PORT variable.
Fix the Django warning You have N unapplied migration(s) on a production server: run migrate in the deploy pipeline, check which migrations are pending, handle migrations missing from the repo, and stop the warning from hiding real problems.
Fix Django DataError value too long for type character varying(N) on PostgreSQL: find the field and the input, raise max_length with a safe migration, validate in forms and serializers, and understand why SQLite never complained.
Fix Permission denied (publickey) and Host key verification failed when GitHub Actions, GitLab CI, or another pipeline deploys Django over SSH: load the private key correctly, add known_hosts, fix authorized_keys permissions, and check the user.
Fix a Django site that runs on the server but times out in the browser: check what listens and on which address, open ufw and cloud firewalls, stop binding to 127.0.0.1, and confirm DNS points at the server.
Fix the plain Bad Request (400) page Django returns in production: DisallowedHost from ALLOWED_HOSTS, invalid HTTP_HOST from health checks, oversized or malformed requests, missing CSRF origins, and how to log the real reason.
Fix 403 Forbidden errors on a Django site in production: tell Nginx 403s from Django 403s, fix CSRF failures, file permissions on static and media, permission checks in views, and WAF or Cloudflare blocks.
Fix the Django ImproperlyConfigured error You’re using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path: set STATIC_ROOT correctly, keep it separate from STATICFILES_DIRS, and run collectstatic in deploys.
Fix the Django 4.0+ system check error 4_0.E001, which says CSRF_TRUSTED_ORIGINS values must start with a scheme: write full origins with https://, use wildcard subdomains correctly, parse the setting from environment variables, and avoid trailing slashes.
Fix the Django runserver error saying you’re accessing the development server over HTTPS but it only supports HTTP: clear cached HSTS, turn off SSL redirects in development, avoid .dev domains, and run local HTTPS properly when you need it.
Fix the Django models.W042 warning about auto-created primary keys: choose between AutoField and BigAutoField for DEFAULT_AUTO_FIELD, avoid surprise migrations on large tables, handle third-party apps, and prepare for the BigAutoField default in Django 6.0.
Fix the Django staticfiles.W004 warning that a STATICFILES_DIRS directory does not exist, and the related E002 error: build paths from BASE_DIR, commit empty directories, check .dockerignore, and keep STATIC_ROOT out of STATICFILES_DIRS.
Fix PermissionError Errno 13 Permission denied for a Django log file such as /var/log/django.log: give the app user ownership, stop root-run commands from creating the file, handle log rotation, or log to stdout instead.
Fix the PostgreSQL error fe_sendauth no password supplied in Django: find why the password is empty, check DATABASE_URL parsing and environment loading in systemd, Docker, and cron, escape special characters, and use .pgpass or secrets safely.
Fix the Django LookupError no installed app with label in production, migrations, and Celery: add the app to INSTALLED_APPS, use the right app label, load the correct settings module, and avoid model imports before Django is ready.
Fix Redis NOAUTH Authentication required and WRONGPASS invalid username-password pair errors in Django and Celery: put the password in the Redis URL correctly, URL-encode special characters, use ACL usernames, and keep cache and broker settings in sync.
Fix Docker no space left on device during Django image builds and deploys: measure what docker system df reports, prune build cache, images, and volumes safely, set log limits, and stop CI runners and servers from filling up again.
Fix the Docker error exec /usr/local/bin/docker-entrypoint.sh exec format error for Django containers: rebuild for the right CPU architecture with buildx, fix Windows line endings and missing shebangs, and verify image platforms before deploy.
Fix Docker Compose errors Bind for 0.0.0.0:8000 failed port is already allocated and address already in use for Django, Postgres, and Redis: find the process or container holding the port, remove orphans, and stop publishing ports you do not need.
Fix Django, Gunicorn, and Celery output missing from docker logs or appearing late: set PYTHONUNBUFFERED, log to stdout instead of files, configure Gunicorn access and error logs, and keep LOGGING from silencing django.request errors.
Fix the Heroku Python build error while running python manage.py collectstatic --noinput: read the hidden traceback, set STATIC_ROOT, avoid settings that need runtime config vars at build time, and fix WhiteNoise manifest errors.
Fix Heroku push rejected, failed to compile Python app for Django: set the Python version with .python-version, fix requirements and lock files, resolve packages that need system libraries, and clear a stale build cache.
Fix Django SMTP errors such as SSL WRONG_VERSION_NUMBER, STARTTLS extension not supported, and connection unexpectedly closed: match EMAIL_PORT with EMAIL_USE_TLS or EMAIL_USE_SSL, and test the provider’s port from the server.
Fix Sentry showing no events from a production Django app: check the DSN and environment, initialize sentry-sdk early in settings, make sure Celery and Gunicorn workers initialize too, and look for sampling, filters, rate limits, and blocked outbound traffic.
Fix ImportError cannot import name force_text, smart_text, ugettext_lazy, url, or ifequal after a Django upgrade: map each removed API to its replacement, upgrade third-party packages that still use them, and catch removals in CI before deploying.
Fix the Nginx 502 error connect() to unix:/run/gunicorn.sock failed (2: No such file or directory): start the Gunicorn socket or service, match the socket path in Nginx and systemd, and stop PrivateTmp and RuntimeDirectory from hiding the file.
Fix the Nginx emerg error could not build server_names_hash, you should increase server_names_hash_bucket_size when adding long domain names or many Django sites: set the bucket and max size in the http block, test, and reload safely.
Fix the browser error ERR_SSL_PROTOCOL_ERROR or SSL_ERROR_RX_RECORD_TOO_LONG for a Django site: find which layer answers HTTPS with plain HTTP, fix listen 443 ssl in Nginx, port mappings, proxy upstream schemes, and cached HSTS for development servers.
Fix the Phusion Passenger error page We’re sorry, but something went wrong / Web application could not be started for Django on cPanel: set up passenger_wsgi.py correctly, use the app’s virtualenv, read the stderr log, and fix static files and restarts.
Fix git fatal detected dubious ownership in repository during Django deploys, CI jobs, and Docker builds: understand the safe.directory check, run git as the repository owner, fix ownership, or add a narrow safe.directory entry.
Fix Host key verification failed when a GitHub Actions workflow deploys Django over SSH: add the server’s host key to known_hosts from a secret, avoid StrictHostKeyChecking=no, handle rebuilt servers and custom ports, and verify fingerprints.
Fix Django SQLite errors attempt to write a readonly database and unable to open database file in production: give the app user write access to the database file and its directory, use an absolute path, and handle Docker volumes and read-only images.
Fix Celery beat failing with ERROR: Pidfile (celerybeat.pid) already exists. Seems we’re already running? after container or server restarts: disable the pidfile in Docker, place it in /run under systemd, and make sure only one beat runs.
Fix Celery errors No result backend is configured and DisabledBackend object has no attribute _get_task_meta_for in Django: configure CELERY_RESULT_BACKEND, load settings with the CELERY namespace, or stop calling .get() on tasks that do not need results.
A 502 Bad Gateway in a Django deployment usually means your reverse proxy is reachable, but it cannot get a valid response from the upstream app server.
Fix Nginx connect() failed (111: Connection refused) to Gunicorn: service status, bind address mismatches, stale sockets, firewalls, and startup ordering.
Fix Permission denied on a Gunicorn Unix socket: socket ownership and mode, directory traversal, systemd RuntimeDirectory, umask, and SELinux.
A Gunicorn worker timeout in Django production usually means a worker process stopped responding before Gunicorn’s timeout limit expired.
Database connection errors in Django production usually appear right after a deploy, after a restart, or after an infrastructure change such as rotating secrets, moving PostgreS...
A common production failure is that the Django web app is healthy, but Celery tasks stop running.
If a Django file upload fails with 413 Request Entity Too Large, the rejection usually happens before Django sees the request. In a production stack like:
Diagnose Django 504 Gateway Timeout errors behind Nginx: find the slow layer, align proxy and Gunicorn timeouts, fix slow views, and offload long work.
Fix Django collectstatic failures: missing STATIC_ROOT, broken CSS references, source map errors, duplicate paths, permissions, and build-time settings.
Fix ERR_TOO_MANY_REDIRECTS on Django behind Nginx, a load balancer, or Cloudflare: SECURE_PROXY_SSL_HEADER, forwarded headers, and duplicate redirects.
Fix PostgreSQL sorry, too many clients already errors from Django: count connections by source, fix CONN_MAX_AGE and worker math, find idle leaks, and add pooling.
Fix Celery tasks that stay PENDING in Django: missing result backends, workers not consuming queues, routing mismatches, unregistered tasks, and commit timing.
Fix Redis connection refused errors from Django caches, sessions, Celery, and Channels: service status, bind addresses, Docker hostnames, TLS URLs, auth, and limits.
Fix Certbot renewal failures for Django sites on Nginx: dry runs, timer checks, HTTP-01 challenge paths, redirects, firewalls, DNS changes, and reload hooks.
Fix browser CORS errors calling a Django API: django-cors-headers setup, middleware order, preflight requests, credentials, and errors without CORS headers.
Fix Django logins that do not stick behind a proxy or HTTPS: secure cookies, HTTPS detection, cookie domains, SameSite, and shared session backends.
Fix Django containers that exit or restart-loop on start: exit codes and logs, CMD and entrypoint mistakes, missing env vars, and database readiness.
Fix a Gunicorn service for Django that systemd cannot start: status codes 203/EXEC, 200/CHDIR, 217/USER, environment files, socket directories, and restart loops.
Fix Django RequestDataTooBig, TooManyFieldsSent, and TooManyFilesSent errors: what each upload limit measures, raising limits safely per endpoint, and proxy limits.
Recover a Django server with a full disk: find what uses space, clean logs, journal, Docker images, and old releases safely, handle open files, add alerts.
Fix Django static files returning 404 in Docker: collectstatic in the image, shared volumes between Django and Nginx, bind mounts hiding files, and WhiteNoise setup.
Get the real client IP in Django behind Nginx, load balancers, or CDNs: X-Forwarded-For parsing, trusted proxy counts, Nginx realip, and spoofing risks.
Fix Celery periodic tasks running twice in Django: duplicate Beat processes, -B on workers, overlapping deploys, duplicate schedules, and redelivery.
Fix AccessDenied from S3 when django-storages uploads files: IAM policy actions, bucket policies, Object Ownership and ACLs, KMS keys, and credentials.
Fix load balancer health checks that mark healthy Django servers down: DisallowedHost 400s, HTTPS redirects, auth on health paths, and slow checks.
Fix 502 errors caused by Nginx 'upstream sent too big header': measure Django's response headers, raise proxy_buffer_size safely, and shrink oversized cookies, sessions, and headers.
Fix Django PostgreSQL TLS errors: no pg_hba.conf entry with no encryption, server does not support SSL, root.crt missing for verify-full, certificate verify failed, and SSL SYSCALL EOF drops.
Fix slow first requests after a Django deploy or restart: measure cold versus warm, find heavy imports with -X importtime, precompile bytecode, preload, warm workers, and avoid cold starts.
Fix Celery WorkerLostError 'Worker exited prematurely: signal 9 (SIGKILL)' in Django: find OOM kills and short stop timeouts, cap memory per child, chunk big tasks, and redeliver safely.
Fix Redis OOM command not allowed when used memory exceeds maxmemory in Django: find what fills Redis, choose the right eviction policy for cache versus Celery, set TTLs, and split instances.
Fix SSL CERTIFICATE_VERIFY_FAILED when Django calls external APIs: incomplete server chains, missing CA bundles in containers, certifi versus the system store, internal CAs, proxies, and clock skew.
Understand and fix Nginx 499 status codes in front of Django: find the slow endpoints and impatient clients, align load balancer and proxy timeouts, and move long work to background tasks.
Fix UnicodeEncodeError 'ascii' codec errors that appear only in production: check Python's encodings, set a UTF-8 locale or PYTHONUTF8 for systemd, cron, and Docker, and pass explicit encodings.
Fix the Celery KeyError and Received unregistered task of type message in Django: make workers import the same task modules as the web app, align task names, and stop stale queued messages from old releases.
Fix Celery SoftTimeLimitExceeded and TimeLimitExceeded errors in Django: find why tasks run long, set soft and hard limits that fit the work, clean up on the soft limit, and split slow jobs into chunks.
Fix Celery worker memory that grows until the OOM killer strikes: recycle children with max-tasks-per-child and max-memory-per-child, find the task that leaks, and avoid DEBUG query logging and large result sets.
Fix Django's 'Conflicting migrations detected; multiple leaf nodes' error: merge or re-parent migrations in development, handle already-applied branches, and block conflicts in CI before deploy.
Fix Apps not loaded yet and settings not configured errors in Celery workers, cron scripts, and Gunicorn config: set DJANGO_SETTINGS_MODULE, call django.setup() first, and avoid early model imports.
Fix Celery Beat that runs but never sends periodic tasks in Django: check that Beat is actually running, the scheduler and timezone settings, django-celery-beat database schedules, stale schedule files, and queue routing.
Fix OSError Errno 24 Too many open files in Gunicorn, Celery, and Nginx: read the real per-process limit, find descriptor leaks with lsof, and raise LimitNOFILE, worker_rlimit_nofile, or Docker ulimits.
Fix Celery tasks that raise Model.DoesNotExist for an object the view just created: queue tasks with transaction.on_commit, understand ATOMIC_REQUESTS, read replicas, and pass IDs instead of model instances.
Fix the Redis ERR max number of clients reached error in Django and Celery: count connections per process, cap connection pools, set timeouts for idle clients, and raise maxclients and file limits safely.
Fix PermissionError Errno 13 when a non-root Django container writes to media or data volumes: numeric UIDs, named volume initialisation, bind mount ownership, SELinux labels, and rootless mappings.
Fix the Redis MISCONF error that blocks writes from Django and Celery: find why background saves fail (disk full, permissions, memory overcommit), restore writes safely, and decide whether the instance needs persistence at all.
Fix a Django cache that never hits in production: confirm the configured backend, avoid LocMemCache across processes, understand why Vary Cookie and CSRF break per-view caching, and check keys, versions, and timeouts.
Stop Django deploys from logging everyone out: a changed or per-process SECRET_KEY, cache-backed sessions lost on restart, changed cookie settings, and rotating keys safely with SECRET_KEY_FALLBACKS.
Fix the Nginx error upstream prematurely closed connection while reading response header from upstream: find the Gunicorn worker that died or timed out, match timeouts across layers, and fix crashes and memory kills.
Fix Celery workers that keep executing old task code after a Django deploy: restart every worker gracefully, check which release each worker runs, and keep task signatures compatible across versions.
Fix the Nginx no live upstreams while connecting to upstream error for Django: understand max_fails and fail_timeout, find why every backend was marked down, and configure upstream health and retries safely.
Speed up Django admin changelists and forms on tables with millions of rows: avoid full counts, add list_select_related, use autocomplete and raw ID fields, index search and ordering, and limit filters.
Fix Let’s Encrypt rate limit errors such as too many certificates already issued for this exact set of domains and too many failed authorizations: stop reissuing on every deploy, persist certificates, and use the staging environment.
Fix high CPU usage on a Django server: find whether Gunicorn, PostgreSQL, Celery, or something else is burning CPU, profile hot endpoints with py-spy, fix N+1 queries and missing indexes, and block abusive traffic.
Fix Django IntegrityError duplicate key value violates unique constraint on the id column after loaddata, a restore, or a migration from another database: reset PostgreSQL sequences with sqlsequencereset or setval.
Fix Django migrate failing with permission denied for schema public on PostgreSQL 15 and newer: make the app role own the database or schema, grant CREATE on public, and set up roles correctly on managed databases.
Fix Django OperationalError 2006 MySQL server has gone away and 2013 lost connection: align CONN_MAX_AGE with wait_timeout, enable CONN_HEALTH_CHECKS, close connections in long-running scripts, and raise max_allowed_packet.
Fix Django DataError 1366 Incorrect string value when saving emoji or other 4-byte characters to MySQL: convert databases, tables, and columns to utf8mb4, set the connection charset, and handle index length limits.
Fix a Django Docker container stuck in unhealthy status: debug the HEALTHCHECK command, use a health endpoint that works without curl, ALLOWED_HOSTS and HTTPS redirects, start_period for migrations, and dependent services.
Fix uWSGI no python application found, check your startup logs for errors: point module at the right wsgi.py, set chdir and virtualenv, load the Python plugin, and read the import error hidden earlier in the log.
Fix the uWSGI error invalid request block size behind Nginx for Django: use uwsgi_pass instead of proxy_pass for the uwsgi protocol, match socket and http-socket, and raise buffer-size for large cookies and headers.
Fix Django SynchronousOnlyOperation You cannot call this from an async context: use async ORM methods, sync_to_async for blocking code, avoid lazy relation access in async views and consumers, and never disable the check in production.
Fix Django Channels WebSocket connections that drop after about 60 seconds of inactivity: raise Nginx proxy_read_timeout, configure load balancer idle timeouts, and send keepalive pings from the client or server.
Fix Django StreamingHttpResponse and server-sent events that arrive all at once instead of streaming: disable Nginx proxy buffering with X-Accel-Buffering, avoid GZip middleware on streams, and use async views for long streams.
Fix Pillow errors when uploading images to Django in production: Cannot use ImageField because Pillow is not installed, decoder jpeg not available, cannot identify image file, DecompressionBombError, and HEIC uploads.
Fix Django redirects that send users to localhost, 127.0.0.1, or an internal hostname behind Nginx or a load balancer: forward the Host header, use USE_X_FORWARDED_HOST correctly, and fix LOGIN_REDIRECT_URL and absolute URLs.
Fix Django request.build_absolute_uri and is_secure returning http behind an HTTPS proxy: set SECURE_PROXY_SSL_HEADER, forward X-Forwarded-Proto from Nginx or the load balancer, and fix OAuth callbacks, API pagination links, and emails.
Fix a Django virtualenv that breaks after upgrading Ubuntu or Debian or changing the Python version: errors like No module named encodings and bad interpreter, recreating the venv safely, and avoiding downtime during the switch.
Fix Cloudflare Error 521 web server is down and Error 522 connection timed out in front of Django: check that Nginx listens, allow Cloudflare IPs through the firewall, match the SSL mode to the origin, and fix origin DNS records.
Fix Cloudflare Error 524 a timeout occurred for slow Django views: understand the 100-second proxy limit, move exports and reports to Celery with polling, stream responses, and bypass the proxy for genuinely long admin tasks.
Fix Heroku H12 Request timeout errors for Django: understand the 30-second router limit, find slow views, set Gunicorn timeouts below it, move long work to worker dynos with Celery or RQ, and avoid H13 cascades.
Fix a Django pod stuck in CrashLoopBackOff on Kubernetes: read logs from the previous container, find missing environment variables and secrets, failing liveness probes, OOMKilled limits, and migrations run at startup.
Fix the Django warning Session data corrupted and users being logged out: find SECRET_KEY changes and mismatches between servers, use SECRET_KEY_FALLBACKS for rotation, and align session engines and serializers.
Fix Django migrate failing with relation already exists, table already exists, or DuplicateTable: compare the schema with migration history, use migrate --fake or --fake-initial correctly, and avoid faking migrations that were never applied.
Fix Django test suites that pass on your machine but fail in GitHub Actions or GitLab CI: PostgreSQL service containers and health checks, missing settings and secrets, static files manifest errors, time zones, and test ordering.
Fix botocore NoCredentialsError Unable to locate credentials in Django with django-storages or SES: give the process an IAM role or environment credentials, fix systemd and Docker env loading, IMDSv2 hop limits, and region settings.
Fix uploads replacing each other on S3 or R2 with django-storages: understand AWS_S3_FILE_OVERWRITE, generate unique upload_to paths, avoid cache-stale files at the same URL, and recover overwritten objects with bucket versioning.
Fix Google, GitHub, and Microsoft OAuth redirect_uri_mismatch errors after deploying Django with django-allauth or social-auth: register the exact production callback URL, force https behind a proxy, and fix host and trailing-slash differences.
Fix Django showing times hours off in production: understand USE_TZ and UTC storage, set TIME_ZONE correctly, activate per-user time zones, render local times in templates, and stop cron and Celery schedules from drifting.
Fix the Django ValueError saying the database returned an invalid datetime value and asking whether time zone definitions for your database are installed: load MySQL or MariaDB time zone tables, including on Docker, RDS, and Cloud SQL.
Fix the PostgreSQL FATAL error no pg_hba.conf entry for host when Django connects: add the right host or hostssl rule, match the client address and auth method, reload PostgreSQL, and handle Docker networks and SSL-only managed databases.
Fix the Django OperationalError server closed the connection unexpectedly: find whether PostgreSQL crashed, a firewall or load balancer killed idle connections, or a failover happened, then tune CONN_MAX_AGE, CONN_HEALTH_CHECKS, and TCP keepalives.
Fix the PostgreSQL error could not resize shared memory segment No space left on device in Docker and Kubernetes: raise /dev/shm with shm_size or a memory-backed emptyDir, and tune parallel query and work_mem for Django workloads.
Fix the PostgreSQL error database is being accessed by other users when Django tests, restores, or resets drop a database: find the open sessions, stop app processes and pools, terminate backends, or use DROP DATABASE WITH (FORCE).
Fix the PostgreSQL InternalError current transaction is aborted, commands ignored until end of transaction block in Django: find the first failing query, use atomic savepoints around expected errors, and clean up after exceptions in tests and workers.
Fix the PostgreSQL error permission denied to create extension when Django migrations add pg_trgm, unaccent, hstore, citext, or PostGIS: create extensions as an admin once, use trusted extensions, and handle RDS, Cloud SQL, Azure, and Supabase.
Fix the Django migration error column contains null values when adding a non-nullable field or changing null=True to null=False: backfill data first, split the change into safe migrations, and keep deploys working on large PostgreSQL tables.
Fix the Django NodeNotFoundError saying migration dependencies reference a nonexistent parent node: restore deleted or uncommitted migration files, repair dependencies after squashing or renaming apps, and handle third-party app version mismatches.
Fix the Django ImproperlyConfigured error AUTH_USER_MODEL refers to model that has not been installed: check the app_label.ModelName format, INSTALLED_APPS, import order, and what to do when switching to a custom user model on an existing database.
Fix the MySQL error 1071 Specified key was too long; max key length is 767 or 3072 bytes in Django migrations: understand utf8mb4 index limits, use InnoDB DYNAMIC rows, shorten indexed CharFields, or index a prefix.
Fix MySQL error 1040 Too many connections from Django: count connections per Gunicorn worker, Celery process, and thread, tune max_connections and wait_timeout, set CONN_MAX_AGE sensibly, and add ProxySQL or RDS Proxy when apps scale out.
Fix the Redis error LOADING Redis is loading the dataset in memory after restarts or failovers in Django and Celery: understand RDB and AOF load time, make the cache degrade gracefully, add retries, and keep cache data out of persistence.
Fix the Redis error READONLY You can’t write against a read only replica in Django and Celery: point clients at the primary endpoint, handle failovers with Sentinel or managed endpoints, and stop stale DNS and connection pools from writing to replicas.
Fix SSL CERTIFICATE_VERIFY_FAILED errors when Django, Celery, or Channels connect to Redis over rediss:// on Heroku, Upstash, ElastiCache, or Azure: configure ssl_cert_reqs, CA bundles, and broker_use_ssl without disabling verification blindly.
Fix pip install failing during a Django Docker build with Temporary failure in name resolution or Failed to establish a new connection: diagnose Docker DNS, corporate proxies, VPNs, and IPv6, and configure daemon DNS or build-time proxy arguments.
Fix Django Docker builds that fail or crawl on python:alpine: understand musl and missing wheels, install the right build packages for psycopg, Pillow, and cryptography, or switch to python:slim for faster, smaller, more reliable images.
Fix Django CSS and JavaScript that stay old after a Docker deploy because a named volume hides the new collectstatic output: understand how volumes shadow image files, collect at the right time, and share static files with Nginx correctly.
Fix Kubernetes readiness and liveness probes that fail with 400 Bad Request because Django rejects the pod IP as a DisallowedHost: add a host header to the probe, exempt the health endpoint safely, or allow the pod network without disabling host checks.
Fix Kubernetes ImagePullBackOff and ErrImagePull for Django pods: read the pull error, fix image names and tags, add imagePullSecrets for GHCR, ECR, or GitLab, handle expiring ECR tokens and rate limits, and match image architecture to nodes.
Fix Kubernetes CreateContainerConfigError for Django pods: find the missing Secret, ConfigMap, or key in the pod events, create it in the right namespace, fix envFrom and secretKeyRef names, and order resources so deploys do not race their config.
Fix Heroku R14 Memory quota exceeded and R15 errors for Django: measure memory per Gunicorn worker, set WEB_CONCURRENCY to fit the dyno, recycle workers with max-requests, find leaks in views and Celery, and choose a dyno size that matches.
Fix Vercel 500 FUNCTION_INVOCATION_FAILED and serverless function crashed errors for Django: read the function logs, expose the WSGI app correctly, fix ALLOWED_HOSTS, static files, database connections, and bundle size limits.
Fix DigitalOcean App Platform deploys that fail with health check failed or container exited for Django: bind Gunicorn to the right port, configure the HTTP health check path, allow the internal host, give migrations a pre-deploy job, and size the instance.
Fix SignatureDoesNotMatch and The authorization mechanism you have provided is not supported, please use AWS4-HMAC-SHA256 in django-storages: set the bucket region and signature version, fix presigned URLs, clock skew, and custom endpoints for R2, Spaces, and MinIO.
Fix the S3 error AccessControlListNotSupported, the bucket does not allow ACLs, in django-storages: stop sending ACL headers with default_acl None, use bucket policies for public static files, and keep private media behind presigned URLs.
Understand and fix Gunicorn log lines such as Error handling request, Ignoring EPIPE, and BrokenPipeError with Django: tell client disconnects apart from real errors, align proxy and Gunicorn timeouts, and handle slow uploads and streaming responses.
Fix Django REST Framework returning authentication credentials were not provided because the Authorization header never reaches Django: enable WSGIPassAuthorization in mod_wsgi, check Nginx and load balancer header forwarding, and test with curl at each hop.
Fix custom request headers such as X_API_KEY or tenant_id disappearing behind Nginx: understand why Nginx ignores headers with underscores, rename them to use hyphens, or enable underscores_in_headers, and read them correctly in Django’s request.headers.
Fix Nginx emerg errors such as cannot load certificate BIO_new_file() failed, no such file, or key values mismatch: check certificate paths, Certbot live symlinks, file permissions, PEM formats, and that the key matches the certificate.
Fix the Nginx alert worker_connections are not enough while connecting to upstream for Django: count client and upstream connections, raise worker_connections and worker_rlimit_nofile, use upstream keepalive, and find slow responses that hold connections open.
Fix Django Channels WebSocket connections rejected with 403 or closed with code 1006 in production: configure AllowedHostsOriginValidator and ALLOWED_HOSTS, pass Host and Origin through Nginx, and check authentication middleware and CSRF-like origin rules.
Fix Django errors after a deploy such as AttributeError Can’t get attribute on module, ModuleNotFoundError, or TypeError when reading cached objects: version cache keys per release, avoid pickling model instances, and clear or namespace the cache safely.
Fix Django SuspiciousFileOperation errors such as the joined path is located outside of the base path component and detected path traversal attempt: build upload paths safely, avoid absolute names and leading slashes, and handle static files referenced with ../.
Fix the Apache mod_wsgi error Target WSGI script cannot be loaded as Python module for Django: match mod_wsgi to your Python version, set python-home and python-path, fix permissions on the project and virtualenv, and read the real exception below it.
Fix django.db.utils.InterfaceError connection already closed in Celery tasks, management commands, and long-running scripts: call close_old_connections, set CONN_MAX_AGE and CONN_HEALTH_CHECKS, and handle database restarts and idle timeouts.
Fix the GeoDjango ImproperlyConfigured error could not find the GDAL library (tried gdal, GDAL...) on servers and in Docker: install GDAL, GEOS, and PROJ system packages, set GDAL_LIBRARY_PATH when needed, and match library versions to Django.
Fix WeasyPrint OSError cannot load library gobject-2.0-0, libpango, or libharfbuzz when generating PDFs in Django on Docker, Heroku, or a slim server: install Pango and fonts, use the right package names, and keep PDF rendering in a worker.
Fix Cloudflare Error 525 SSL handshake failed and Error 526 invalid SSL certificate in front of Django: match the SSL/TLS mode to the origin, install a valid or Origin CA certificate on Nginx, open port 443, and check SNI and expiry.
Fix AWS ECS tasks that stop with Essential container in task exited for Django on Fargate or EC2: read the stopped reason and CloudWatch logs, fix missing secrets and permissions, health check failures, exit codes 137 and 1, and migration commands.
A failed Django migration during deploy usually means your release reached production, but the database change step did not finish cleanly.
Diagnose Gunicorn workers killed for running out of memory: OOM evidence, memory per worker, large querysets, leaks, max-requests, and right-sizing.
Debug Django Channels WebSocket failures behind Nginx: handshake status codes, Upgrade headers, ASGI routing, origin checks, wss mixed content, and idle timeouts.
Fix Django InconsistentMigrationHistory errors safely: read the dependency message, compare history with files, handle custom user models, avoid data loss.
Fix a Django migrate command that hangs during deploy: find the blocking PostgreSQL session with pg_blocking_pids, stop the lock queue from taking the site down, and set lock_timeout.
Fix Celery tasks that run two or three times with a Redis broker: understand visibility_timeout, ETA and countdown redelivery, acks_late, and make long or scheduled tasks safe from duplicate execution.
Find and fix PostgreSQL sessions stuck 'idle in transaction' from Django: identify the source with application_name, fix atomic blocks around slow work, and set idle_in_transaction_session_timeout.
Fix PostgreSQL 'cannot execute INSERT in a read-only transaction' in Django: writes sent to a replica or reader endpoint, stale connections after failover, database routers, and read-only settings.
Find and fix a Django memory leak in production: tell real leaks from normal Python growth, recycle Gunicorn workers, profile with tracemalloc, and fix DEBUG query logging, unbounded caches, and large querysets.
Fix PostgreSQL deadlock detected errors in Django apps: read the deadlock log, lock rows in a consistent order with select_for_update, shorten transactions, and retry the transactions that lose.
Fix intermittent and constant 502 Bad Gateway errors from an AWS Application Load Balancer in front of Django: keepalive timeouts shorter than the ALB idle timeout, unhealthy targets, security groups, and HTTP/HTTPS target mismatches.
Fix the PostgreSQL error canceling statement due to conflict with recovery when Django reads from a hot standby: understand vacuum conflicts, tune max_standby_streaming_delay and hot_standby_feedback, and route long reports to the right replica.
Fix PostgreSQL pg_wal growing until the disk is full on a Django database: find inactive replication slots, broken WAL archiving, or high max_wal_size, free space safely without deleting WAL by hand, and add alerts so it does not happen again.
Fix the PostgreSQL warning database has a collation version mismatch after upgrading Ubuntu, Debian, or a Docker base image under a Django database: reindex affected text indexes, refresh the collation version, and avoid silent index corruption.
Fix MySQL error 1205 Lock wait timeout exceeded; try restarting transaction in Django: find the blocking transaction, shorten long atomic blocks, avoid gap locks from unindexed filters, and handle select_for_update and migrations safely.
Fix PostgreSQL errors SSL error decryption failed or bad record mac and SSL SYSCALL error EOF detected in Celery workers or preloaded Gunicorn: stop sharing database connections across fork, close connections before forking, and use per-process connections.