Django’s handling of media files such as images, css, etc. has confused me from the very beginning. I’m not going to claim that I fully understand the full ramifications yet, but at least I got something working… hopefully it’ll be helpful for someone. I’m running Django from an Apache 2.0.59 server, and I will be serving media files from the same apache server. The Django documentation suggests that a separate webserver for serving media files will boost performance significantly… which is good, since it gives me something to worry about if I run out of things to do 🙂
I’ve checked out my copy of Django to /home/djangosrc and created a symbolic link in Python’s site-packages directory to /home/djangosrc/django.
My Django server lives in /home/django and I’ve got media files in /home/django/media, and template files in /home/django/templates.
I created a virtual host on Apache and set it up for Django:
<VirtualHost 184.108.40.206:80> ServerName www.mydomain.com ServerAdmin firstname.lastname@example.org <Location "/"> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE datakortet.settings PythonPath "['/home/django'] + sys.path" PythonDebug on </Location>
Then I created a symbolic link from the Apache DocumentRoot directory (htdocs) to the media files for the admin interface: ln -s /home/djangosrc/django/contrib/admin/media htdocs/admin_media. In the settings.py file I put: ADMIN_MEDIA_PREFIX = ‘/admin_media/’ I’m pretty sure this tells Django that it should look for the admin interface media files in http://www.mydomain.com/admin_media/ (the first part of the url coming from the server Django is running on). Continuing the virtual host definition to reflect this I got
<Location "/admin_media"> SetHandler none </Location> <LocationMatch "\.(jpg|gif|png)$"> SetHandler none </LocationMatch>
For regular media files I added a symbolic link in Apache’s htdocs directory to my media directory: ln -s /home/django/media htdocs/media, then over in settings.py I added MEDIA_ROOT = ‘/home/django/media’ and MEDIA_URL = ‘http://web.datakortet.no/media’, and finally I could finish off the virtual host definition with:
<Location "/media"> SetHandler none </Location> </VirtualHost>
So far it seems to be working well. The next project in my queue requires uploading of image files, so I haven’t tested that yet, but hopefully I’m not too far off..