Change The Django Source Directory With A .pth File
Monday, February 11th, 2008John DeRosa recently wrote about using junctions (the Windows version of a symbolic link within Unix) to change the Django source directory. While that solution clearly works, I got the impression it seemed like a lot of hard work and John asked if there was a better way of handling that scenario.
If you’re wondering why a developer might want different versions of Django installed - it’s common if you need to upgrade an existing site from one version to another or if you offer a distributed application that is meant to work on the latest and also older versions of Django.
Under normal circumstances, developers place a copy of the Django source code underneath their ${install_path}\Lib\site-packages\ folder. While this works, it isn’t particularly convenient if you want or need to switch between the different versions. Under a unix based system, the common way of switching between the different versions is using a symbolic link; so you’d change the symbolic link from pointing from version A to version B. Unfortunately, in a Windows environment the concept of a symbolic link either doesn’t exist or isn’t common knowledge. As a by product, the average developer is only left with the option of copy and pasting the Django source code around in their file system or renaming folders - not particular convenient.
Fortunately, a little known feature of Python is that it supports special files with a .pth file extension. The .pth files or path files, are using by the site module (found under ${install_path}\Lib\) when the interpreters environment is initialised. The .pth files are standard text files, which contain one path per line, which when loaded are added into the sys.path collection.
A quick run down, place a django.pth file under ${install_path}\Lib\site-packages\, with a single line pointing towards your preferred Django source code version. When you need to change the version of Django you’re developing against - change the path within the file. Remember that if you have a Python interpreter open at the time, you’ll need to restart it and likewise if you’re running Django via something like Apache.