Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 273
Joe J Avatar asked Jun 27 '12 18:06

Joe J


2 Answers

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.

like image 63
jdi Avatar answered Sep 22 '22 15:09

jdi


why not keep the staticfiles functionality and simply use rewrites at the web server level to serve up the content.

for instance:

rewrite /css /static permanent; (for nginx) 

this would keep your project directory a lot cleaner and also make it easier to move your static directories around in the future, for instance to move to your STATIC_URL to a CDN.

like image 28
blsmth Avatar answered Sep 22 '22 15:09

blsmth