Python and Postgres Peculiarities Deploying Django on Heroku

I've been working with Python and Django lately, and have enjoyed learning both. With each step deeper, however, you start to appreciate the debugging practice, whether due to newbie mistakes or straight up platform configuration issues.

I highly recommend this "Crash Course" from pycon2014 put on by Kenneth Love that runs through the setup of a Django app and a base CMS, and a final deployment to Heroku.

While trying to perform the final push, I ran into some problems installing a critical adapter (psycopg2) that allows for a local dev instance running sqlLite to work on Heroku's remote PostGres database. The problem occurs on a bare OS, but also seems to be persistent when using virtualenv for python (which you are using, right?)

I'm using virtualenv and virtualenvwrapper on OSX, running Mavericks. (Make sure you are working on your virtualenv when running these steps - workon [envName]

First step to getting up and running is to install PostGres locally. For that I recommend Postgres.app which has been conveniently put together for us.

Next - we need to find the local compiled path for our config file so we can pass it to psycopg and set it in our PATH:
sudo find / -name "pg_config" -print

The return from the above will look something like this:
/Applications/Postgres.app/Contents/Versions/9.3/bin

Using that string, we can now set up the correct path to pg_config in our terminal:
PATH=/Applications/Postgres.app/Contents/Versions/9.3/bin:$PATH

Now try re-installing psycopg again:
pip install psycopg2

and that should resolve to success:

       Successfully installed psycopg2
       Cleaning up...

Congrats!

Before declaring victory, however, let's make sure that our requirements.txt file correctly reflects that psycopg is installed:

Django==1.6.2  
South==0.8.4  
dj-database-url==0.3.0  
django-braces==1.4.0  
django-crispy-forms==1.4.0  
django-debug-toolbar==1.2  
gunicorn==18.0  
mistune==0.2.0  
six==1.6.1  
sqlparse==0.1.11  
whitenoise==1.0.2  
psycopg2==2.5.1   <<< HERE IT IS

Now we can perform our push to Heroku and perform a successful heroku run python manage.py syncdb without those pesky psycopg errors.

If you're using South, After running syncdb make sure you take care of any migrations, otherwise prod will be unhappy.
heroku run python manage.py migrate

Hopefully that's useful for people running into issues with their initial deployments.

Questions? Comments? Withering criticism? Let me know below.

Want to build great things with cool people? We're Hiring.

Author

Seph Coster

Geek, father, sailor, wonk. Experienced public sector technology consultant, ocean racer, and diaper changer.

comments powered by Disqus