Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure Django's "staticfiles" app to list directory contents?

I'm using Django's built-in web server, in DEBUG mode.

This is part of my settings.py:

STATIC_ROOT = '/home/user/static_root'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    '/abs/path/to/static/dir',
)
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

If I access http://localhost:8000/static/png/, I would expect to see a list of files available in /abs/path/to/static/dir/png. Instead I get a 404 error "Directory indexes are not allowed here."

Now if I access the files directly, e.g. http://localhost:8000/static/png/test.png, it works.

I've already checked some answers (here) without success.

So, does anyone know how to configure Django such that the staticfiles app lists directory contents?

like image 617
E.Z. Avatar asked May 15 '13 12:05

E.Z.


People also ask

How do I access Django media files?

Unfortunately, the Django development server doesn't serve media files by default. Fortunately, there's a very simple workaround: You can add the media root as a static path to the ROOT_URLCONF in your project-level URLs.

How do I setup a static file?

Configuring static filesMake sure that django.contrib.staticfiles is included in your INSTALLED_APPS . In your templates, use the static template tag to build the URL for the given relative path using the configured STATICFILES_STORAGE . Store your static files in a folder called static in your app.

What is STATICFILES_DIRS?

STATICFILES_DIRS is the list of folders where Django will search for additional static files aside from the static folder of each app installed.


1 Answers

Just for completeness since it might help others, this is what I did to solve the problem.

Following @Hedde's answer, I went to use show_indexes:

settings.py

  • Kept all the configuration the same (i.e. all the STATIC* variables)
  • Removed 'django.contrib.staticfiles' from INSTALLED_APPS

The problem is that I cannot specify the show_indexes parameter using Django's "built-in" method for static file configuration (via settings.py). By having 'django.contrib.staticfiles' in INSTALLED_APPS, Django would create the static file handler with show_indexes = False, ignoring my urlpatterns.

urls.py

Added the following to urlpatterns:

url(regex  = r'^%s(?P<path>.*)$' % settings.STATIC_URL[1:], 
    view   = 'django.views.static.serve', 
    kwargs = {'document_root': '/abs/path/to/static/dir',
              'show_indexes' : True})
like image 68
E.Z. Avatar answered Nov 09 '22 09:11

E.Z.