Shri
Shri

Reputation: 731

Using Psycopg2 in virtualenv (Ubuntu 14.4, Python 3.4)

I have installed postgres and Psycopg2 using apt-get on my linux.

I want to use postgres for one of my django project.

I have created virtualenv but i am not able to work with psycopg2 when i add it in db settings.

Here is setting.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'secondnginxapp',
        'USER': 'myprojectuser',
        'PASSWORD': 'postgres',
        'HOST': '127.0.0.1',
        'PORT': '',
    }
}

I run the server and got the error Error loading psycopg2 module: No module named 'psycopg2'

I check installed psycopg2 with following command.

 python -c "import psycopg2; print(psycopg2.__version__)"

Output: 2.4.5 (dt dec mx pq3 ext)

How to use psycopg2 with virtualenv? need help.

(I am learning python and django)

I tried to install in virtualenv as well.

pip install psycopg2 then error is Error: b'You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application.\n'

Then i tried pip install libpq-dev now error is No matching distribution found for libpq-dev

Upvotes: 2

Views: 816

Answers (2)

Morishiri
Morishiri

Reputation: 884

The solution is to install server version of postgresql (It seems like you have only client installed). On Ubuntu:

sudo apt-get install postgresql-server-dev-X.Y

where the X.Y is version of the package.

Then, inside virtualenv environment install psycopg2 module:

pip install psycopg2

This should work.

Upvotes: 1

Burhan Khalid
Burhan Khalid

Reputation: 174622

The problem here is that you have used apt-get to install the driver, which has installed it in your system python's package directory; and by default the virtual environment is created with no system packages.

So even though the command works when you are outside the virtual environment (using the system Python), it doesn't work inside the virtual environment.

You have two options to fix this:

  1. Delete the file no-global-site-packages.txt found in your virtual environment's Python installation.

    So if you created a virtual environment at /home/env/my-env/, then you would execute rm /home/env/my-env/lib/python3.4/no-global-site-packages.txt

    Once that file is removed, the virtual environment will look in the global environment for any missing packages.

  2. Install the system libraries that will allow you to build the extension. For ubuntu this is sudo apt install build-essential python-dev python3.4-dev libpq-dev. Once you run that command, you can then pip install psycopg2 in your virtual environment.

Upvotes: 2

Related Questions