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

此生再无相见时 提交于 2019-12-17 20:52:10

问题


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?


回答1:


'show_indexes': True

As per the documentation




回答2:


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})



回答3:


Those files are not meant to be served by django. Show indexes is a configuration parameter of apache/nginx.

In production, with nginx, just add to the static serving part :

    location ^~ /static/ {
            autoindex on;
            root /var/www/static_dir;
            if ($query_string) {
                    expires max;
            }
    }

For dev environnement, Hedde's answer is indeed the good answer, but the display may not be the exact same than the one offered by your HTTP server. Don't rely on it's look&feel.




回答4:


From https://docs.djangoproject.com/en/1.5/ref/views/#django.views.static.serve ...

static.serve(request, path, document_root, show_indexes=True)  


来源:https://stackoverflow.com/questions/16564864/how-to-configure-djangos-staticfiles-app-to-list-directory-contents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!