Setting up PostgreSQL and Django on OS X

I've been keen to start using PostgreSQL for far too long now. Everyone raves about it and MySQL has lost it's open source cred since being acquired by Oracle.

But I was quickly starting to believe that the reason people were raving about it (particularly Python and Ruby folk) was simply because they were just so proud of themselves for having managed to set it up locally.

So for my own sanity, here's my back to basics guide for installing and setting up PostgreSQL, creating a database and connecting to it via the command line and Django.

If you haven't already got Homebrew installed, explain yourself:

$ /usr/bin/ruby -e "$(curl -fsSL"

If you already do, a quick update is always a good idea:

$ brew update
$ brew doctor

And then install PostgreSQL:

brew install postgresql

As part of that installation script Homebrew will try and run the initial setup for you. The command is something like (NB Homebrew runs this for you, you don't have to):

$ initdb /usr/local/var/postgres -E utf8

In my case though, I was getting an error saying could not change permissions of directory "/usr/local/var/postgres": Operation not permitted

So I simply chowned that directory then ran brew postinstall postgresql which got everything working.

Next, I created the database itself. I assumed this was a command that was run from the PostgresSQL command prompt, but no, it's a shell script:

$ createdb database_name

Now, if you want to access this database via the command line you can use the following command (it's also a nice sanity check):

$ psql database_name

With a PostgreSQL install and a database created it's time to turn our attention to Django.

Assuming you have virtual environment up and running with Django and you are in your Django directory you need to install psycopg2

I use Python3. For some reason there seems to be an issue with psycopg2 and Python versions so I specifically used pip3 to install it:

$ pip3 install psycopg2

And then added my database to my settings file:

    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'database_name',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '5432',

And finally you can run your migrations:

$ python migrate

Now you should probably go off an create a test database as well.