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

  1. It isn't in requirements.txt. It was installed in your virtualenv but never recorded.
  2. 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 with Error: pg_config executable not found.
  3. A mismatch with the Python version. An old pinned psycopg2-binary has no wheel for your newer Python.
  4. 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

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

Get startedSee pricing

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.