Search code examples
djangostatic-filesdjango-staticfiles

Media files are served, static files aren't


I'm stuck due to an evergreen issue, static files not served. Conversely the files placed in the MEDIA_ROOT subtree get served correctly under MEDIA_URL.

Stripped settings.py:

DEBUG = True
STATIC_URL = '/static/'
STATIC_ROOT = '/home/foo/devel/static'
MEDIA_URL = '/media/'
MEDIA_ROOT = '/home/foo/devel/media'
# the following is deprecated but is it seems grappelly requires it
ADMIN_MEDIA_PREFIX = STATIC_URL + "grappelli/"
STATIC_FILES = ()
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

To create the project I did:

$ cd /home/foo/devel/
$ virtualenv testdrive
$ . bin/activate; pip install django; cd testdrive
$ django-admin.py fbtest

and got this directory tree (stripped):

. <-- /home/foo/devel/
├── bin
├── fbtest
│   └── fbtest
│       ├── media
│       │   └── foo.jpg
│       ├── static
│       └────── foo.jpg
├── include
└── lib

Files under STATIC_URL should be served automatically by Django staticfiles (not in my case), while other files have to be handled manually. So I appended these lines to urls.py:

import settings
if settings.DEBUG:
    urlpatterns += patterns('',
        url(r'^%s(?P<path>.*)$' % settings.MEDIA_URL.lstrip("/"),
            'django.views.static.serve', {
            'document_root': settings.MEDIA_ROOT,
        }),
    )

Accessing http://host/media/filebrowser/foo.jpg works, while http://host/static/foo.jpg gives error 404. Why?


Solution

  • It was a silly error. I forgot to add fbtest to INSTALLED_APPS, so the static file machinery didn't manage static files for this app.