116

I'm new to Python and Django.

I'm configuring a Django project using a PostgreSQL database engine backend, But I'm getting errors on each database operation. For example when I run manage.py syncdb, I'm getting:

C:\xampp\htdocs\djangodir>python manage.py syncdb
Traceback (most recent call last):
  File "manage.py", line 11, in <module>
    execute_manager(settings)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line
438, in execute_manager
    utility.execute()
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line
379, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line
261, in fetch_command
    klass = load_command_class(app_name, subcommand)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line
67, in load_command_class
    module = import_module('%s.management.commands.%s' % (app_name, name))
  File "C:\Python27\lib\site-packages\django\utils\importlib.py", line 35, in im
port_module
    __import__(name)
  File "C:\Python27\lib\site-packages\django\core\management\commands\syncdb.py"
, line 7, in <module>
    from django.core.management.sql import custom_sql_for_model, emit_post_sync_
signal
  File "C:\Python27\lib\site-packages\django\core\management\sql.py", line 6, in
 <module>
    from django.db import models
  File "C:\Python27\lib\site-packages\django\db\__init__.py", line 77, in <modul
e>
    connection = connections[DEFAULT_DB_ALIAS]
  File "C:\Python27\lib\site-packages\django\db\utils.py", line 92, in __getitem
__
    backend = load_backend(db['ENGINE'])
  File "C:\Python27\lib\site-packages\django\db\utils.py", line 33, in load_back
end
    return import_module('.base', backend_name)
  File "C:\Python27\lib\site-packages\django\utils\importlib.py", line 35, in im
port_module
    __import__(name)
  File "C:\Python27\lib\site-packages\django\db\backends\postgresql\base.py", li
ne 23, in <module>
    raise ImproperlyConfigured("Error loading psycopg module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading psycopg module: No mo
dule named psycopg

Can someone give me a clue on what is going on?

Boann
  • 48,794
  • 16
  • 117
  • 146
André
  • 24,706
  • 43
  • 121
  • 178

13 Answers13

225

You need to install psycopg2 Python library.

Installation


Download http://initd.org/psycopg/, then install it under Python PATH

After downloading, easily extract the tarball and:

$ python setup.py install

Or if you wish, install it by either easy_install or pip.

(I prefer to use pip over easy_install for no reason.)

  • $ easy_install psycopg2
  • $ pip install psycopg2

Configuration


in settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'db_name',                      
        'USER': 'db_user',
        'PASSWORD': 'db_user_password',
        'HOST': '',
        'PORT': 'db_port_number',
    }
}

- Other installation instructions can be found at download page and install page.

Optimus Prime
  • 6,817
  • 5
  • 32
  • 60
Alireza Savand
  • 3,462
  • 3
  • 26
  • 36
  • 2
    Hi, I follow your instruction but it seems I should create the user/pwd pair before I use them in the settings.py? – Yulong Jun 18 '12 at 15:15
  • @Yulong you have to create an `user` for postgres, but password is not necessary. – Alireza Savand Jun 18 '12 at 15:24
  • 2
    but I get this `psycopg2.OperationalError: fe_sendauth: no password supplied` when I run `python manage.py syncdb`. I set random table name and user name. – Yulong Jun 18 '12 at 15:29
  • @Yulong I have never exprience such an error about it, but maybe this help you. https://groups.google.com/forum/?fromgroups#!topic/django-users/Sx3WLelcyEg Let me know if it solved the issue. – Alireza Savand Jun 18 '12 at 15:32
  • I will try it. for now since i am trying a heroku deployment I will first find if there is a heroku-compatible way. but still thanks for the quick reply! – Yulong Jun 18 '12 at 15:37
  • Is it Python 3.3 compatible? – Green Jan 24 '13 at 17:48
  • If you want to use it with Django, No it's not. Django itself is not compatible with python3 yet, I think psycopg2 is compatible with python3, You have to compile it yourself. Look at this comment: http://initd.org/psycopg/articles/2012/03/29/psycopg-245-released/#c92 – Alireza Savand Jan 24 '13 at 18:26
  • make sure you have `python-dev` installed for `psycopg2`. Might be obvious to most people but it tripped me up on a recent server config. – bnjmn Jul 31 '13 at 15:51
  • All psycopg2 links are dead – RedRory Dec 04 '13 at 19:08
  • 1
    @RedRory Thanks, They're fine now ;) – Alireza Savand Dec 04 '13 at 23:38
  • what is "django & python PATH"? – Thumbz Jun 26 '14 at 06:35
  • 2
    FYI: As of Django 1.9 you can say: 'ENGINE': 'django.db.backends.postgresql', – powlo Apr 02 '16 at 17:20
  • @powlo Thanks for the comment, I have updated the post regarding to it. – Alireza Savand Apr 03 '16 at 04:12
  • In Mojave (OS X 10.14) `pip install psycopg2` did not initially work for me (python 3.7, django 2.2). See detailed solution here: https://stackoverflow.com/a/57014480/2162844 – Bisonbleu Jul 12 '19 at 22:13
  • 2
    The problem that I had with this answer is that `django.db.backends.postgresql` dosn't work with `psycopg2`. what worked is `django.db.backends.postgresql_psycopg2` back end and avoided specifying port number as it change every time you start pgAdmin on windows – Mustapha-Belkacim Aug 01 '19 at 21:35
31

Also make sure you have the PostgreSQL development package installed. On Ubuntu you need to do something like this:

$ sudo apt-get install libpq-dev
Dennis Bunskoek
  • 461
  • 4
  • 3
27

Step by step that I use:

 - sudo apt-get install python-dev
 - sudo apt-get install postgresql-server-dev-9.1
 - sudo apt-get install python-psycopg2 - Or sudo pip install psycopg2

You may want to install a graphic tool to manage your databases, for that you can do:

sudo apt-get install postgresql pgadmin4 

After, you must change Postgre user password, then do:

 - sudo su
 - su postgres -c psql postgres
 - ALTER USER postgres WITH PASSWORD 'YourPassWordHere';
 - \q

On your settings.py file you do:

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

Extra:

If you want to create the db using the command line you can just do:

- sudo su
- su postgres -c psql postgres
- CREATE DATABASE dbname;
- CREATE USER djangouser WITH ENCRYPTED PASSWORD 'myPasswordHere';
- GRANT ALL PRIVILEGES ON DATABASE dbname TO djangouser;

On your settings.py file you do:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'dbname',
        'USER': 'djangouser',
        'PASSWORD': 'myPasswordHere',
        'HOST': '',
        'PORT': '',
    }
}
Gregory
  • 6,514
  • 4
  • 28
  • 26
7

You can install "psycopg" with the following command:

# sudo easy_install psycopg2

Alternatively, you can use pip :

# pip install psycopg2

easy_install and pip are included with ActivePython, or manually installed from the respective project sites.

Or, simply get the pre-built Windows installer.

Sridhar Ratnakumar
  • 81,433
  • 63
  • 146
  • 187
Sandro Munda
  • 39,921
  • 24
  • 98
  • 123
  • 2
    Or `sudo apt-get install python-psycopg2` if you are on a Debian system and want to use the package manager rather than pip/easy_install. – Blair Mar 23 '11 at 01:31
6

This may seem a bit lengthy, but it worked for me without any error.

At first, Install phppgadmin from Ubuntu Software Center.

Then run these steps in terminal.

sudo apt-get install libpq-dev python-dev
pip install psycopg2
sudo apt-get install postgresql postgresql-contrib phppgadmin

Start the apache server

sudo service apache2 start

Now run this too in terminal, to edit the apache file.

sudo gedit /etc/apache2/apache2.conf

Add the following line to the opened file:

Include /etc/apache2/conf.d/phppgadmin

Now reload apache. Use terminal.

sudo /etc/init.d/apache2 reload

Now you will have to create a new database. Login as 'postgres' user. Continue in terminal.

sudo su - postgres

In case you have trouble with the password of 'postgres', you can change it using the answer here https://stackoverflow.com/a/12721020/1990793 and continue with the steps.

Now create a database

createdb <db_name>

Now create a new user to login to phppgadmin later, providing a new password.

createuser -P <new_user>

Now your postgressql has been setup, and you can go to:

http://localhost/phppgadmin/

and login using the new user you've created, in order to view the database.

Community
  • 1
  • 1
Jibu James
  • 1,581
  • 14
  • 11
5

The immediate problem seems to be that you're missing the psycopg2 module.

hd1
  • 33,938
  • 5
  • 80
  • 91
aptwebapps
  • 1,866
  • 1
  • 13
  • 17
4

If you are using Fedora 20, Django 1.6.5, postgresql 9.3.* and you need the psycopg2 module, do this:

yum install postgresql-devel
easy_install psycopg2

If you are like me, you may have trouble finding the well documented libpq-dev rpm... The above worked for me just now.

secretformula
  • 6,414
  • 3
  • 33
  • 56
3

I was having the same Issue on Mac.

The solution was to use only PIP to install everything, and touch some things.

First install PIP from: https://pip.pypa.io/en/latest/

Then you want to make sure if path to pg_config is in your PATH (echo $PATH), if not you can edit your bash_profile:

vi /Users/<user>/.bash_profile

and add this line:

export PATH=$PATH:/path/to/pg_config/bin

If you don't know where pg_config is you can use the "locate" tool, but be sure your locate.db is up to date (i was using an old locate.db and using paths that does not exists).

sudo /usr/libexec/locate.updatedb
locate pg_config

Then install Django (if needed) and psycopg2.

sudo pip install Django
sudo pip install psycopg2

And then in settings.py (localhost:defaultport)

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

Greets!

2
$ sudo apt-get install libpq-dev

Year, this solve my problem. After execute this, do: pip install psycopg2

Gregory
  • 6,514
  • 4
  • 28
  • 26
2

Steps to create a Django app with PostgreSQL database from scratch.

  1. Check if PostgreSQL is installed in your system. In your bash shell enter

    psql --version
    
  2. If PostgreSQL is installed jump to step 6.

  3. To install PostgreSQL -

    sudo apt-get install python3-dev libpq-dev
    
    sudo apt-get install postgresql postgresql-contrib
    
  4. By default PostgreSQL installation creates a special user named "postgres" that has all rights. To login to PostgreSQL

    sudo -u postgres psql
    

    To exit PostgreSQL session

    \q
    
  5. Now set password for "postgres" user.

    Login to PostgreSQL -

    sudo -u postgres psql
    

    In PostgreSQL interactive session enter -

    \password postgres
    
  6. Create PostgreSQL database.

    To create directly from bash shell -

    sudo -u postgres createdb your_db_name
    

    To create from PostgreSQL interactive session -

    createdb your_db_name
    

    To check if the database is created, list all databases using PostgreSQL command

    \l
    
  7. If you already have an existing Django project then jump to step 11. Otherwise create a virtual environment. I use virtualenv wrapper.

    mkvirtualenv your_project_name
    
  8. Create Django project.

    django-admin startproject your_project_name
    
  9. Cd to the project directory and create your app.

     python manage.py startapp your_app_name
    
  10. Install Django.

    pip install django
    
  11. Install Psycopg2. Psycopg2 is a PostgreSQL database adapter for Python. This is required for Django to connect with PostgreSQL.

    pip install psycopg2
    
  12. Update settings.py as follows

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'your_db_name',
            'USER': 'postgres',
            'PASSWORD': 'xxxxx',
            'HOST': 'localhost',
            'PORT': '',
        }
    }
    
  13. Run migration.

    python3 manage.py migrate
    
  14. Run Django server and visit localhost:8000

    python3 manage.py runserver 0.0.0.0:8000
    
  15. If required you can install pgadmin - a graphical client to view and manipulate PostgreSQL database schema and data.

ABN
  • 1,024
  • 13
  • 26
0

Please note that installation of psycopg2 via pip or setup.py requires to have Visual Studio 2008 (more precisely executable file vcvarsall.bat). If you don't have admin rights to install it or set the appropriate PATH variable on Windows, you can download already compiled library from here.

Sergey Ivanov
  • 3,719
  • 7
  • 34
  • 59
  • What about this? Microsoft Visual C++ Compiler for Python 2.7 ==>> https://www.microsoft.com/en-us/download/details.aspx?id=44266 – Ajeeb.K.P May 14 '15 at 06:01
0

This is one of the very good and step by step process to set up PostgreSQL in ubuntu server. I have tried it with Ubuntu 16.04 and its working.

https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-14-04

sgauri
  • 694
  • 8
  • 18
-2

postgres runs on port 5432

specify this in settings.py

https://www.postgresql.org/docs/14/app-postgres.html

Harry Moreno
  • 10,231
  • 7
  • 64
  • 116
vforv
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 27 '22 at 19:23