Django, PYTHONPATH, and iPython

After trying Drupal and finding it needlessly twisted, I have decided to experiment with Django. I’m working my way through Python Web Development with Django┬«, by Jeff Forcier, Paul Bissex and Wesley Chun, published by Addison-Wesley Professional in 2008. Thing have gone smoothly, so far, though I have not yet set up Apache to work with Python and Django either locally or on my server. My previous experience has been limited using Python for cgi scripting.

I followed the Django installation instructions at to install Django 1.2.5 (current version is 1.3), generally without a hitch. Following instructions in Appendix B of the book, I ran the command python install from the Django directory. Also at the suggestion of the book, I installed iPython. It has some handy features, but also seems to have far more features than I need. I’ve also had a problem with its recognizing my Django directory as part of its search path. The regular Python editor does not have this problem.

To inspect the search path, start python:

$ python
Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path

This should print out a mutable list of paths. The problem is, the list is different if you invoke ipython as the editor. In fact, it’s missing the path that contains the Django library. As a result typing

>>> import django

in iPython will return an error message. It works just fine in the regular old Python editor.

The remedy? For scripts that are run from the Terminal, you need to create or modify the PYTHONPATH environmental variable, which stores the search path returned by sys.path in Python. Even if you haven’t set this variable, the standard Python editor apparently gets all the necessary information from other path variables in Mac OSX, while iPython doesn’t. It seems to be missing one specific path. To add it in, edit your ~/.bash_profile file to contain the following line:

export PYTHONPATH=/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages:$PYTHONPATH

You can add other paths to this later on, as you develop your own modules. Other techniques for adding to the search path involve .pth files or, for apps launched from the finder, creating or modifying ~/.MacOSX/environment.plist.

0 Responses to “Django, PYTHONPATH, and iPython”

  • No Comments

Leave a Reply

You must be logged in to post a comment.