Configuring Django and PostgreSQL on Ubuntu

This morning, I set up a Django development environment again on my laptop running Ubuntu. Although I have done this several times in the past, I still run into errors occasionally. There are a few differences compared to setup on a Mac using homebrew, and a couple of additional dependencies to install.

Everytime I do this, I search online and trawl through a few websites to jog my memory. This post should give anyone a concise but complete overview of how to configure Django and PostgreSQL on Ubuntu, and double up as a reference for me in the future. I'm running Ubuntu 13.10.

1. Update packages

Make sure all packages are up to date before starting.

# sudo apt-get update && sudo apt-get upgrade

2. Install and create a virtual environment

# sudo apt-get install python-virtualenv

Change to the working directory and create a virtual environment. I usually keep my projects under  ~/Projects. The following command will create a virtual environment under ~/Projects/djangoapps.

# virtualenv djangoapps

3. Install PostgreSQL

# sudo apt-get install postgresql

Next, install some development libraries that are required for PostgreSQL to work with Django.

# sudo apt-get install libpq-dev python-dev

4. Create database and user

In this step, we'll create the database and a user. We will then grant the user access to the database that was created.

First, the database:

# sudo su - postgres
# createdb mydb

Next, the user:

# createuser -P
Enter name of role to add: django_user
Enter password for new role:
Enter it again:
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) n
Shall the new role be allowed to create more new roles? (y/n) n

Grant django_user privileges to mydb.

# psql
psql (9.1.11)
Type "help" for help.

postgres=# GRANT ALL PRIVILEGES ON DATABASE mydb TO django_user;

5. Install and configure Django

Now, we can install and configure Django. Change to the directory where the virtual environment was created (~Projects/djangoapps in this example) and activate it.

# . ./bin/activate

You'll see '(djangoapps)' prepended to the shell prompt. Install Django and psycopg2 which is required for Django to connect to the PostgreSQL database:

# pip install django
# pip install psycopg2

Create a new django project.

# startproject myproject

Change to the new "myproject/myproject" directory that has been created for you, and edit the databases section in Replace 'mypassword' with the password entered when the user was created in step 4.

'default': {
'NAME': 'mydb',
'USER': 'django_user',
'PASSWORD': 'mypassword',
'HOST': '',
'PORT': '5432',

Finally, move up one directory and run syncdb.

# python syncdb

If everything works, Django will create its initial configuration tables at this point and prompt you to create a superuser.

That's it. Now, create a new app and start developing!