Irrational Exuberance!

When psycopg2 Can't Import tz

February 13, 2009. Filed under failpostgresql

I have frequently run into this (or similar) error message:

File "/home/django/domains/", line 16, in <module>
    backend = __import__('%s%s.base' % (_import_path, settings.DATABASE_ENGINE), {}, {}, [''])
File "/home/django/domains/", line 20, in <module>
    raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
ImproperlyConfigured: Error loading psycopg2 module: cannot import name tz

And each time I am very confused by it. Then I realize the problem. Then I solve it. Then I forget about it. Until the next time.

Your server cannot write to the PYTHON_EGG_CACHE path, and thus cannot use eggs. That's the entire problem right there. Although you might need to install egenix-mx-base. I'm not even sure if it's relevant or just something I want to be relevant as I tirelessly struggle against this error.

sudo easy_install egenix-mx-base

The real fix to this problem is in either your mod_python or mod_wsgi configuration files. For mod_wsgi a line like this should be added to your site's .wsgi file.

os.environ['PYTHON_EGG_CACHE'] = '/home/django/.python-eggs'

It doesn't need to be home/django/.python-eggs specifically, just somewhere that www-data can write to (for Ubuntu). To check just su to www-data and give it a wack.

sudo su www-data
cd /home/django/.python-eggs
mkdir test
rm -rf test

If that worked, then you're golden. Restart your server and get outa here. If you're using mod_python, then you'll need to make this change in a different location. It's explained more fully here, but basically you need to make a file somewhere that contains these lines

import os
os.environ['PYTHON_EGG_CACHE'] = '/home/django/.python-eggs'

And then add these directives to your domain's VirtualHost.

PythonInterpreter my_django
PythonImport /path/to/my/profile/ my_django

Then you're done. Phew. I hope I never get thrown for a loop by this silly error again.