3
respostas

Error loading psycopg2 module: No module named 'psycopg2'

Não consigo compilar o projeto. O psycopg2 e psycopg2-binary foram corretamente instalados na venv, mas o erro abaixo está sendo apresentado.

/usr/local/bin/python3.8 /Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevconsole.py --mode=client --port=65022
import sys; print('Python %s on %s' % (sys.version, sys.platform))
import django; print('Django %s' % django.get_version())
sys.path.extend(['/Users/danielmirandacruz/PycharmProjects/aplicacao/alurareceita', '/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm', '/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev'])
if 'setup' in dir(django): django.setup()
import django_manage_shell; django_manage_shell.run("/Users/danielmirandacruz/PycharmProjects/aplicacao/alurareceita")
PyDev console: starting.
Python 3.8.3 (v3.8.3:6f8c8320e9, May 13 2020, 16:29:34) 
[Clang 6.0 (clang-600.0.57)] on darwin
Django 3.0.7
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 25, in <module>
    import psycopg2 as Database
  File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
ModuleNotFoundError: No module named 'psycopg2'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "<input>", line 6, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate
    app_config.import_models()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models
    self.models_module = import_module(models_module_name)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/Users/danielmirandacruz/PycharmProjects/aplicacao/alurareceita/receitas/models.py", line 6, in <module>
    class Receita(models.Model):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/base.py", line 121, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/base.py", line 325, in add_to_class
    value.contribute_to_class(cls, name)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/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 "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/__init__.py", line 28, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/utils.py", line 207, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/utils.py", line 111, in load_backend
    return import_module('%s.base' % backend_name)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 29, in <module>
    raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2'
3 respostas

Oi Daniel, como você está? Espero que esteja tudo bem ^-^

Quando você digita o comando pip list dentro do ambiente virtual, o psycopg2 é listado? Exemplo:

image

Caso ele não apareça na lista, tente-o instalar novamente, pois o log de erro aponta que o mesmo não está instalado no ambiente virtual. Também fiz algumas simulações e obtive o mesmo erro que você quando eu não possuía ambas dependências(psycopg2 e psycopg2-binary) em meu ambiente virtual.

Ative o ambiente virtual:

Linux: source nome_do_ambiente/bin/activate

Windows: nome_do_ambiente/Scripts/Activate

E para instalar os pacotes, tente o seguinte:

pip3 install psycopg2
pip3 install psycopg2-binary

Fico à disposição. Abraços e bons estudos!

Executei o comando e aparece o pycopg2 instalado. Mas ainda assim com erro. Uso mac.

(venv) danielmirandacruz@MacBook-Pro-de-Daniel alurareceita % pip list
Package         Version
--------------- -------
asgiref         3.2.7
Django          3.0.7
pip             20.1.1
psycopg2        2.8.5
psycopg2-binary 2.8.5
pytz            2020.1
setuptools      47.3.1
sqlparse        0.3.1
(venv) danielmirandacruz@MacBook-Pro-de-Daniel alurareceita %

Daniel, tente o seguinte:

  • Ative seu ambiente virtual

  • Desinstale ambos o pacotes psycopg2 e psycopg2-binary:

pip uninstall psycopg2-binary
pip uninstall psycopg2
  • Agora execute o pip list e confirme se esses pacotes foram desinstalados.

  • Instale novamente os pacotes:

pip install psycopg2
pip install psycopg2-binary

Tente executar novamente o projeto:

python manager.py runserver

Caso ainda não dê certo, vamos excluir a venv e fazê-la novamente, tá bom?

  • Exclua a pasta venv

  • Crie um novo ambiente virtual dentro da pasta do projeto:

python -m venv venv
  • Ative o ambiente virtual:
source nome_do_ambiente/bin/activate
  • Instale as bibliotecas: django, psycopg2 e psycopg2-binary
pip install django
pip install psycopg2
pip install psycopg2-binary
  • Agora, tente novamente executar o projeto:
python manager.py runserver

Fico no aguardo, vamos conversando =)