In This Week in Django 2 – 2007-12-16 I mentioned in closing that I often use Unipath to keep things portable. This is not an original idea of mine, but just something I picked up from some open source project somewhere. I’d give credit, but quite honestly I merely adopted it as my own and never thought about it again.
When handling the serving of static images while using the built-in webserver, I’ll often use Unipath to be able to point to the location of my media directory, that usually exists inside of my Project directory. For example:
from django.views.static import serve
from unipath import FSPath as Path
if settings.DEBUG:
urlpatterns += patterns('',
(r'^m/(?P<path>.*)$', serve, {'document_root' : Path(__file__).parent.child("media")}),
)
This code is pretty straight forward. I’m just getting the path to the file I’m in, in this case it’s urls.py in the project folder, and then I’m getting the parent folder and then its child named media.
My folder structure looks something like this:

You’ll notice that the highlighted file is the urls.py module that the above code resides in.
The really cool thing about this approach is that the directory structure is portable. So if I were to move the project directory to another location, everything still works.
Incidentally you can do the same thing using the os.path class, if you find that Unipath is not your “cup of tea”. For instance:
import os
from django.views.static import serve
if settings.DEBUG:
urlpatterns += patterns('',
(r'^m/(?P<path>.*)$', serve, {'document_root' : os.path.join(os.path.dirname(__file__), "media")}),
)
Unipath makes it easy to work with file, path, and filesystem calls in an object-oriented manner. According to the documentation, the Path class is also being proposed as an addition to the standard library.
I haven’t experienced any issues with this approach thus far. Give it a try.

