Django: Auto-generating a list of files in a directory
I use an image gallery app on my website. At present I drop image files in a directory, and write img html tags for each image manually. Is it possible to make django create a list of files in the directory automa开发者_运维知识库tically, and send the json output to the gallery app, so that I can make javascript to generate <img>
elements for each image files. Or, whenever gallery app is requested, can I directly make django to auto-generate <img>
elements for each of the files in a directory.
here's a bit of code for you:
views.py
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})
gallery.html
{% for image in images %}
<img src='/static/{{image}}' />
{% endfor %}
import os
from django.conf import settings
from annoying.decorators import ajax_request
@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 = [
re_path(
r'^media/(?P<path>.*)$',
serve,
{
'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>
<ul>
{% if directory != "./" %}
<li><a href="../">../</a></li>
{% endif %}
{% for f in file_list %}
<li><a href="{{ f|urlencode }}">{{ f }}</a></li>
{% endfor %}
</ul>
{% endblock %}
See the documentation here: https://docs.djangoproject.com/en/dev/ref/views/#serving-files-in-development
精彩评论