Search code examples
pythondjangodjango-staticfilesstatic-files

Django 1.7 static files directory scanning


Working on a personal project and trying to write a directory scanner with ajax/jquery for images to create a slideshow on a web-page using Django 1.7.

I am getting the standard "Directory indexes are not allowed here." error when trying to view the directory containing the images. Each image itself is served by the static files app correctly but I cannot view the directory to loop through them.

My settings.py file has the following static properties.

STATIC_URL = '/resources/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, "resources"),os.path.join(BASE_DIR, "<app_name>/resources"),)
STATICFILES_FINDERS = (
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
)

Images are located at BASE_DIR/resources/img/frontpage/slideshow/img_name.jpg

I can load each image itself but the url localhost:8000/resources/img/frontpage/slideshow/ returns the "Directory indexes are not allowed here." error.

I've been through several other stack overflow answers and none have solved the problem so I'm reaching out for more experienced django developer help.


Solution

  • In a (correctly configured) production setup, static files are not served by Django but by some frontend server (nginx, apache, whatever), so directory listing is configured on the front server. When working with the builtin dev server, one usually use django's staticfiles app to serve the static files. This app doesn't have any directory listing view but you can easily write one and add it to your urls.py.

    This being said, relying on the front server's directory listing scanning is brittle at best - you depend on the directory listing being allowed and on the specific server's implementation. Why don't you just write a Django view returning a json listing of the directory ? It will take less time than writing the code to "scan" a directory listing and will be much more robust.