Guides / ModuleNotFoundError: No module named 'psycopg2'
ModuleNotFoundError: No module named 'psycopg2'
Your app crashes at startup with ModuleNotFoundError: No module named 'psycopg2' or django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 or psycopg module. Django needs a Postgres driver and your production environment doesn't have one. Or the install failed with pg_config executable not found. Both have simple fixes.
What it means
Django talks to Postgres through a Python driver, psycopg (version 3) or psycopg2. It isn't a dependency of Django, so you have to list it yourself. It worked on your machine because you installed it by hand once.
Why it happens
- It isn't in
requirements.txt. It was installed in your virtualenv but never recorded. - It is listed, but the build fails.
psycopg2(without-binary) compiles C code and needs the Postgres client headers. In a slim image that fails withError: pg_config executable not found. - A mismatch with the Python version. An old pinned
psycopg2-binaryhas no wheel for your newer Python. - The wrong environment runs the app. Dependencies were installed into a different virtualenv than the one gunicorn uses.
The fix
For new projects on Django 4.2 or newer, use psycopg 3 with its prebuilt binaries:
pip install "psycopg[binary]"
# requirements.txt
psycopg[binary]>=3.1
Django uses it with the same engine setting: "ENGINE": "django.db.backends.postgresql". If you must stay on psycopg2:
pip install psycopg2-binary
If you prefer to compile the driver (the psycopg project recommends building it for production), install the system packages first. On Debian or Ubuntu images:
RUN apt-get update \
&& apt-get install -y --no-install-recommends build-essential libpq-dev \
&& rm -rf /var/lib/apt/lists/*
Making it stick in production
- Prove your requirements are complete in a clean environment before deploying:
python -m venv /tmp/check && /tmp/check/bin/pip install -r requirements.txt && /tmp/check/bin/python manage.py check. - Pin versions with a lock file (
pip-compile, oruv lock) so the server installs exactly what you tested. - Match the Python version of the server and of your local environment.
- If other imports fail the same way after a deploy, read ModuleNotFoundError only after deploy.
Or skip it
Django Cloud builds your app from your requirements.txt, or pyproject.toml and uv.lock, as they are, in a clean container, so a missing or broken driver shows up in the build log and not in production.
pip install djangocloud-cli
djangocloud deploy
Free plans are available for students, AWS Activate startups, open-source, non-profit and research projects. See how Django Cloud compares with other ways to host Django.
Django is a registered trademark of the Django Software Foundation. Django Cloud is not affiliated with or endorsed by it. Found a mistake in this guide? Tell us and we will fix it.