Wednesday, August 1, 2012

Install PostgreSQL for Django and Virtualenv on Ubuntu

Install PostgreSQL:

sudo apt-get install postgresql

Later we need to install psycopg2 using pip. To resolve some dependency issues, we need to install libpq-dev and python-dev. For more details, please see here.

sudo apt-get install libpq-dev python-dev

Set password for the "postgres" user.

sudo passwd postgres

Then enter password.

Create a Django dev user:

sudo -u postgres createuser -P django_dev

Enter password.

Add postgres to sudoers:

sudo vi /etc/sudoers

Find the following line:

root ALL=(ALL:ALL) ALL 

Below this line, add the following:

postgres ALL=(ALL) ALL

Now switch to the "postgres" user

su postgres

Enter PostgreSQL shell:

psql postgres

Create a DB:

CREATE DATABASE django_db OWNER django_dev ENCODING 'UTF8';

Type \q to quit the PostgreSQL shell.

Edit the permission file:

sudo vi /etc/postgresql/9.1/main/pg_hba.conf

Your PostgreSQL version number might be different. Replace 9.1 with the correct version number.

Change:

local    all    postgres    peer 
local    all    all    peer

To:

local    all    postgres    md5
local    all    all    md5

And add the following line:

local    django_db    django_dev    md5

Now, restart PostgreSQL server:

sudo /etc/init.d/postgresql restart

Get into virtual env and install psycopg2:

source ~/your_virtual_env/bin/activate
pip install psycopg2

Go to your django project and edit the settings.py file, change the following settings:

'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'django_db', 
'USER': 'django_dev', 
'PASSWORD': 'your_password', 

Finally, at the directory where manage.py is, type the following command to synchronize DB:

python manage.py syncdb


References:

- How to install PostgreSQL on Ubuntu for Django

- PostgreSQL Ubuntu Installation

- PostgreSQL Fatal Authentication Failure

- Add User to "sudoers" File

- PostgreSQL Server Guide

3 comments:

  1. thanks for sharing :) BTW, I also have a blog and a web directory, would you like to exchange links? let me know on emily.kovacs14@gmail.com

    ReplyDelete
  2. Not so far I have found new cool tool to work with PostgreSQL on ubuntu — Valentina Studio. Its free edition can do things more than many commercial tools!!
    I very recommend check it. http://www.valentina-db.com/en/valentina-studio-overview

    ReplyDelete