Joe J Joe J - 1 month ago 21
CSS Question

django staticfiles at url root

I have a general question about the new Django 1.3 static file framework.

I really like the new Django staticfile functionality introduced in Django 1.3. Normally, I set STATIC_URL="/static/" and enter the {{ STATIC_URL }} template tag into my templates. It's great how the development server automatically serves up the static files and all of my content is served up as expected.

The {{ STATIC_URL }} would be substituted in the template and might serve up files like this...
example.com/static/css/master.css
example.com/static/images/logo.png
example.com/static/js/site.js


However, I'm working with a legacy site where the static media is mounted at the url root. For example, the path to the static urls might look something like this:

example.com/css/master.css
example.com/images/logo.png
example.com/js/site.js


It doesn't use the "static" url namespace.

I was wondering if there is a way to get the new staticfile functionality to not use the static namespace and serve the urls above, but still retain the benefits of the new staticfile framework (collectstatic, static files served by development server, etc). I tried setting STATIC_URL="" and STATIC_URL="/", but neither seemed to have the desired effect.

Is there a way to configure static files to serve static files without a namespace? Thanks for your consideration.

jdi jdi
Answer

You can manually add extra locations that do not exist within the static directories within your project:

urls.py

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = patterns('',
    # ... the rest of your URLconf goes here ...
)

if settings.DEBUG:
    urlpatterns += static('/css/', document_root='app_root/path/to/css/')
    urlpatterns += static('/images/', document_root='app_root/path/to/images/')
    urlpatterns += static('/js/', document_root='app_root/path/to/js/')

This will map the media for the DEBUG dev server. And when you are running your production mode server, you will obviously be handling these static locations from the web server instead of sending the request through to django.