05 Dec 2014

Setting up postgres database for django development

Install postgresql postgresql-client packages. Then start the postgresql service.

# service start postgresql

Now run the psql shell as postgres user.

# su - postgres
postgres@localhost$ psql

Create an user that you want to use with django. Here I am going to create database user ragsagar with password s0mestr0ngPassw0rd. Permission to create database is also given to this user by appending CREATDB. If this is not given django tests will fail when it try to create test database while running tests.

postgres=# CREATE USER ragsagar WITH PASSWORD 's0mestr0ngPassw0rd' CREATEDB;
CREATE ROLE

Create a database with the created user as its owner. I am going to create a database with name djangodb

postgres=# CREATE DATABASE djangodb OWNER ragsagar;
CREATE DATABASE

By default postgres will only allow peer authentication for local users. So we have to open the authentication configuration file /etc/postgresql/9.1/main/pg_hba.conf and change the auth method of local users from peer to md5.

Find the line which looks like following

local   all             all                                     peer

And change it to

local   all             all                                     md5

Restart the postgresql service and check if you are able to connect to the database from the shell. It will ask for password and opens a psql shell like shown below.

# service postgresql restart
$ psql -U ragsagar djangodb
Password for user ragsagar: 
psql (9.1.14)
Type "help" for help.

djangodb=> 

Open your django project settings.py file and add the database name, user and password.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'djangodb',
        'USER': 'ragsagar',
        'PASSWORD': 's0mestr0ngPassw0rd',
    }
}

Make migrations and create tables with it.

$ python manage.py makemigrations
$ python manage.py migrate

Now go make awesome webapps with postgres datastore.

Happy Hacking :-)