PostgrestSQL & Python

PostgreSQL is an open source relational database server. As any other server, it takes some confuguring to get it setup. All the instructions given here should be only consider when you developing on your local machine, you may want to improve your security on your development server.

Installing PostgrestSQL

$ sudo apt-get install postgresql postgresql-client


Installing it is a breaze. Configuring it, however, it is a bit more complicated. PostgrestSQL's configuration file can be found in /etc/postgresql/9.1/main/postgresql.conf. Go ahead an take a looks at its contents, for the purposes of this tutorial you will not need to edit any of the contents of the file.

The next step is to create a user. Creating a user with the same credentials as your ubuntu user has an added benefit; when accessing the server from within the user you will not be ask for any credentials.

#postgres is the out of the box superuser

$ sudo -u postgres createuser

#it will prompt you for a name of a role to add, use your ubuntu username

$ Enter name of role to add: myubuntuuser

#make it a super user and grant it all the priviledges. This is a security risk, dont do this on a production server.

$ Shall the new role be a superuser? (y/n) y

#if everything worked as expected you should be able to create a database running this following command.

$ createdb helloworld

Python Bindings

There are various python packages that allow you to natively interact with your PostgreSQL server. You can install the one you prefer. In this example, we will be installing psycopg2

#make sure you are working on the correct virtualenv

$ pip install psycopg


Django Settings

The last step is to modify your django settings to include the following.

DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'helloworld', # name of the database you created. 'USER': '', # Not used if you created a user with the same credentials as your login user. 'PASSWORD': '', # Not used if you created a user with the same credentials as your login user. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } }

I hope you enjoyed this quick tutorial.