How to Solve Error Message ModuleNotFoundError: No module named ‘psycopg2’ in Django

Posted on

Problem that appear in this article is the error message of ‘ModuleNotFoundError: No module named ‘psycopg2’. The error message shows upon executing ‘python manage.py makemigrations’ command in the command line interface. It is a command to migrate any existing models available in the Django-based web application into the associated database and tables. Unfortunately, the command failed and it triggers an error message as it exist in the title of this article. In this article, there will be several steps taken in order to solve the problem. First of all, the following is the actual execution of the command which is triggering the error message :

(myenv) c:\python-win\project>python manage.py makemigrations
Traceback (most recent call last):
File "C:\python-win\myenv\lib\site-packages\django\db\backends\postgresql\base.py", line 25, in 
import psycopg2 as Database
ModuleNotFoundError: No module named 'psycopg2'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "manage.py", line 21, in 
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "C:\python-win\myenv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:\python-win\myenv\lib\site-packages\django\core\management\__init__.py", line 377, in execute
django.setup()
File "C:\python-win\myenv\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\python-win\myenv\lib\site-packages\django\apps\registry.py", line 114, in populate
app_config.import_models()
File "C:\python-win\myenv\lib\site-packages\django\apps\config.py", line 211, in import_models
self.models_module = import_module(models_module_name)
File "c:\python38\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1014, in _gcd_import
File "", line 991, in _find_and_load
File "", line 975, in _find_and_load_unlocked
File "", line 671, in _load_unlocked
File "", line 783, in exec_module
File "", line 219, in _call_with_frames_removed
File "C:\python-win\myenv\lib\site-packages\django\contrib\auth\models.py", line 2, in 
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "C:\python-win\myenv\lib\site-packages\django\contrib\auth\base_user.py", line 47, in 
class AbstractBaseUser(models.Model):
File "C:\python-win\myenv\lib\site-packages\django\db\models\base.py", line 121, in __new__
new_class.add_to_class('_meta', Options(meta, app_label))
File "C:\python-win\myenv\lib\site-packages\django\db\models\base.py", line 325, in add_to_class
value.contribute_to_class(cls, name)
File "C:\python-win\myenv\lib\site-packages\django\db\models\options.py", line 208, in contribute_to_class
self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
File "C:\python-win\myenv\lib\site-packages\django\db\__init__.py", line 28, in __getattr__
return getattr(connections[DEFAULT_DB_ALIAS], item)
File "C:\python-win\myenv\lib\site-packages\django\db\utils.py", line 207, in __getitem__
backend = load_backend(db['ENGINE'])
File "C:\python-win\myenv\lib\site-packages\django\db\utils.py", line 111, in load_backend
return import_module('%s.base' % backend_name)
File "c:\python38\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "C:\python-win\myenv\lib\site-packages\django\db\backends\postgresql\base.py", line 29, in 
raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2'

(myenv) c:\python-win\project>

What is the exact database configuration for connecting Django-based web application to the PostgreSQL Database Server ?. It exist in a configuration file with the name of ‘settings.py’ in the root folder of the project. So, the location of the ‘settings.py’ in this example exist in the following tree command output :

(myenv) C:\python-win\project>tree . /f
Folder PATH listing for volume Windows
Volume serial number is xxxxxxxxxxxx
C:\PYTHON-WIN\PROJECT
│   db.sqlite3
│   manage.py
│
├───system
│   │   asgi.py
│   │   settings.py
│   │   urls.py
│   │   wsgi.py
│   │   __init__.py
│   │
│   └───__pycache__
│           settings.cpython-38.pyc
│           urls.cpython-38.pyc
│           wsgi.cpython-38.pyc
│           __init__.cpython-38.pyc
...
(myenv) C:\python-win\project>

The following is snippet code of the ‘settings.py’ containing the PostgreSQL database connection :

    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'db_app',
        'USER': 'postgres',
        'PASSWORD':'password',
        'HOST':'localhost',
        'PORT':'5432',
    }

The solution is very simple to handle the above error message. Since there is no module which is important as a requirement to finish the migration command above, just add it. So, execute the following command to add the module :

(myenv) c:\python-win\project>pip install psycopg2
Collecting psycopg2
  Downloading psycopg2-2.8.5-cp38-cp38-win_amd64.whl (1.1 MB)
     |████████████████████████████████| 1.1 MB 45 kB/s
Installing collected packages: psycopg2
Successfully installed psycopg2-2.8.5
WARNING: You are using pip version 20.1; however, version 20.1.1 is available.
You should consider upgrading via the 'c:\python-win\myenv\scripts\python.exe -m pip install --upgrade pip' command.

(myenv) c:\python-win\project>

The above output command is a command to install a new module with the name of ‘psycopg2’. Final Result :

(myenv) c:\python-win\project>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying sessions.0001_initial... OK

(myenv) c:\python-win\project>

Try to connect to the database to prove that the associated table and database has exist as a result of the above command execution as follows :

C:\Program Files\PostgreSQL\12\bin>psql -Upostgres
Password for user postgres:
psql (12.2)
WARNING: Console code page (437) differs from Windows code page (1252)
         8-bit characters might not work correctly. See psql reference
         page "Notes for Windows users" for details.
Type "help" for help.

postgres=# \l
                                                 List of databases
   Name    |  Owner   | Encoding |          Collate           |           Ctype            |   Access privileges
-----------+----------+----------+----------------------------+----------------------------+-----------------------
 db_app    | postgres | UTF8     | English_United States.1252 | English_United States.1252 |
 postgres  | postgres | UTF8     | English_United States.1252 | English_United States.1252 |
 template0 | postgres | UTF8     | English_United States.1252 | English_United States.1252 | =c/postgres          +
           |          |          |                            |                            | postgres=CTc/postgres
 template1 | postgres | UTF8     | English_United States.1252 | English_United States.1252 | =c/postgres          +
           |          |          |                            |                            | postgres=CTc/postgres
(4 rows)


postgres=# \c db_app
You are now connected to database "db_app" as user "postgres".
db_app=# \dt
                   List of relations
 Schema |            Name            | Type  |  Owner
--------+----------------------------+-------+----------
 public | auth_group                 | table | postgres
 public | auth_group_permissions     | table | postgres
 public | auth_permission            | table | postgres
 public | auth_user                  | table | postgres
 public | auth_user_groups           | table | postgres
 public | auth_user_user_permissions | table | postgres
 public | django_admin_log           | table | postgres
 public | django_content_type        | table | postgres
 public | django_migrations          | table | postgres
 public | django_session             | table | postgres
(10 rows)


db_app=#

Leave a Reply