Writing Django tests for PostGis

Posted on Sat 24 August 2013 in Tech

PostGis is awesome, I think I already established this in this post. However when you start writing django tests you might start getting errors complaining that certain postgres libs cannot be found. This is because you've failed to create a proper postgres_template database for your test database to work with. Run these commands in your postgres prompt to create the appropriate template.

CREATE DATABASE template_postgis ENCODING='utf-8';
UPDATE pg_database SET datistemplate='true' WHERE datname='template_postgis';
sudo -u postgres psql -d template_postgis -f /usr/share/postgresql/9.1/contrib/postgis-1.5/postgis.sql
sudo -u postgres psql -d template_postgis -f /usr/share/postgresql/9.1/contrib/postgis-1.5/spatial_ref_sys.sql
sudo -u postgres psql -d template_postgis -f /usr/share/postgresql/9.1/contrib/postgis_comments.sql
sudo -u postgres psql -d template_postgis -c 'GRANT ALL ON geometry_columns TO PUBLIC;'
sudo -u postgres psql -d template_postgis -c 'GRANT ALL ON geography_columns TO PUBLIC;'
sudo -u postgres psql -d template_postgis -c 'GRANT ALL ON spatial_ref_sys TO PUBLIC;'

If you decide to name your postgis template something other than template_postgis, make sure you tell Django by putting the below into settings.py

POSTGIS_TEMPLATE = 'my_other_database_template'

Note: I ran all of these commands on my Ubuntu 12.04 LTS vagrant box. If you get encoding errors you might need to set UTF-8 as the template DB encoding, see this SO answer.