[Solved]-Django: Auto-generating a list of files in a directory


here’s a bit of code for you:


import os 

def gallery(request):
    path="C:\\somedirectory"  # insert the path to your directory   
    img_list =os.listdir(path)   
    return render_to_response('gallery.html', {'images': img_list})


{% for image in images %}
<img src='/static/{{image}}' />
{% endfor %}


import os
from django.conf import settings
from annoying.decorators import ajax_request

def json_images(request, dir_name):
    path = os.path.join(settings.MEDIA_ROOT, dir_name)
    images = []
    for f in os.listdir(path):
        if f.endswith("jpg") or f.endswith("png"): # to avoid other files
            images.append("%s%s/%s" % (settings.MEDIA_URL, dir_name, f)) # modify the concatenation to fit your neet
    return {'images': images}

this functions return a json object containing all images in a directory inside MEDIA_ROOT.

require the django-annoying packages 😉


I’m not sure about the earlier versions of Django, but in 4.2, you can use the serve() view from from django.views.static

# urls.py
# ===============================================
from django.views.static import serve
from django.conf import settings
from django.urls import re_path

urlpatterns = [
            'document_root': settings.MEDIA_ROOT,
            'show_indexes': True, # must be True to render file list

serve() will look for a template called static/directory_index.html to render the document list; if it doesn’t find this template, it falls back to a white page with an unordered list of links. The context variables your template receives are directory (which is the relative directory of the list you are viewing) and file_list.

Your directory_index.html might look like this:

# directory_index.html
# ===============================================
{% extends "base.html" %}

{% block content %}
  {{ block.super }}
  <h1>{{ directory }}</h1>
    {% if directory != "./" %}
      <li><a href="../">../</a></li>
    {% endif %}
    {% for f in file_list %}
      <li><a href="{{ f|urlencode }}">{{ f }}</a></li>
    {% endfor %}
{% endblock %}

See the documentation here: https://docs.djangoproject.com/en/dev/ref/views/#serving-files-in-development

Leave a comment