简体   繁体   中英

trouble with python manage.py migrate -> No module named psycopg2

I am having some trouble with migrating Django using postgresql.

This is my first time with Django, and I am just following the tutorial.

As suggested on the Django website, I have created a virtualenv to run the Django project.

Next, I created a postgresql database with these settings:

在此处输入图片说明

In settings.py I have set these values for the database:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'django_tutorial',
        'USER': 'johan',
        'PASSWORD': '1234',
    }
}

When installing psycopg2 with apt-get I get this message:

(venv)johan@johan-pc:~/sdp/django_tutorial/venv/django_tutorial$ sudo apt-get install python-psycopg2
Reading package lists... Done
Building dependency tree       
Reading state information... Done
python-psycopg2 is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 95 not upgraded.

As far as I can tell this would mean that psycopg2 is installed.

When running

$python manage.py migrate

I get the following error message:

django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2

If needed for the answer I could provide the entire stack trace.

Could someone explain what I could do to solve this? I have also looked on Google for a solution with no luck.

It must be because you are installing psycopg2 in your system level python installation not in your virtualenv.

sudo apt-get install python-psycopg2

will install it in your system level python installation.

You can install it in your virtualenv by

pip install psycopg2

after activating your virtualenv or you can create your virtualenv with --system-site-packages flag so that your virtualenv will have packages in your system level python already available.

virtualenv --system-site-packages test

where test is your virtualenv.

Psycopg is the most popular PostgreSQL database adapter for the Python programming language. I was also facing a similar problem when I tried to run the migration with Postgresql database. The below step worked for me fine.

Activate your Virtual Environment and run the following command

pip install psycopg2-binary

Now try running python manage.py migrate

It's because you use Django in a python virtualenv and as stated on virtualenv web site :

It creates an environment that has its own installation directories, that doesn't share libraries with other virtualenv environments (and optionally doesn't access the globally installed libraries either).

That means that you need to install psycopg2 in your virtualenv and not globaly or make it access globaly installed libraries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM