Search code examples
djangostatic-filesdjango-staticfilesdjango-1.4

Static file management in Django1.4


I've been confused with static files in Django for days. I found one solution that worked fine. But it collapsed when I set DEBUG=False. So I build up a new project and do some tests to get a clearer look. First I create a project with the default settings. Then I changed some lines of the setting file into:

STATIC_ROOT = '%s/site_media' % PROJECT_DIR
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(STATIC_ROOT, 'images'),
)

After that, I put 'hi.jpg' at 'project_dir/images/hi.jpg'. I call runserver and visit 'http://127.0.0.1:8000/static/images/hi.jpg'. It doesn't work. What's the problem?


Solution

  • Here's how it works: when DEBUG=True then Django serves the static files itself. When DEBUG=False then Django won't do that anymore and you'll need to configure your web server to do it (such as Apache).

    Django has a mechanism for that in django.contrib.staticfiles (see Managing static files and The staticfiles app). It basically means that you need to run the collectstaticmanagement command which will search for all static files in /static/ directories in your Django project and it will put them in one directory (STATIC_ROOT). When that has been done, your web server can serve the static files from that directory.

    If one or more static files can't be found after running collectstatic then that means you have configured something incorrectly.