Django
Table of contents
Serve static files directly from Django
Changes to settings.pyMEDIA_ROOT = '/home/user/devel/mysite/static/' MEDIA_URL = '/static/' ADMIN_MEDIA_PREFIX = '/media/'
Apparently the example code in settings.py is not that good for this purpose, as you need to re-define ADMIN_MEDIA_PREFIX to something else than "/media/" (the default) if you want to use "/media/" for your static files or Django will mix the two URLs up and try to serve your media files from the admin dir.
Instead, simply use a different keyword for your static media files. I will use "static" from now on!
Changes to urls.py
from django.conf import settings
if settings.DEBUG:
urlpatterns += patterns('',
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)Just append this at the bottom of your file, and it will only be active on sites with DEBUG set to true. My production servers have an Apache alias that takes care of /static for these kind of sites, and I even explicitly set the handler to None, to be sure Python/Django never gets the request.
NOTE: This should only be used during development, since both performance and security is questionable.
Apache configuration example
<VirtualHost *:80>
ServerName django.confighell.com
ServerAlias www.django.confighell.com
ServerAdmin webmaster@confighell.com
DocumentRoot /home/user/prod/htdocs
ErrorLog /home/user/prod/logs/error.log
CustomLog /home/user/prod/logs/access.log combined
<Location />
Options None
Order allow,deny
Allow from all
SetHandler python-program
PythonInterpreter custom-site-id
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonOption django.root /mysite
PythonDebug On
PythonPath "['/home/user/prod'] + sys.path"
</Location>
<Location /static>
SetHandler None
</Location>
Alias /static/ /home/user/prod/htdocs/static/
</VirtualHost>Resources
- See http://www.djangoproject.com/
- Online book at http://www.djangobook.com/
