Django:自动生成目录中文件列表
我在我的网站上使用一个图片画廊应用。目前,我需要手动把图片文件放到一个文件夹里,然后为每张图片写一个标签。请问有没有办法让Django自动生成这个文件夹里的文件列表,并把结果以JSON格式发送给画廊应用,这样我就可以用JavaScript来生成每张图片的
元素?或者说,每当画廊应用被请求时,我能不能让Django直接自动生成这个文件夹里每个文件的
元素呢?
3 个回答
0
我不太确定早期版本的Django是怎样的,但在4.2版本中,你可以使用来自 django.views.static
的 serve()
视图。
# 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()
会寻找一个叫做 static/directory_index.html
的模板来显示文件列表;如果找不到这个模板,它就会显示一个空白页面,上面有一串链接的无序列表。你的模板会收到一些上下文变量,其中 directory
是你正在查看的相对目录,而 file_list
则是文件列表。
你的 directory_index.html
可能长这样:
# 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 %}
想了解更多,可以查看这里的文档: https://docs.djangoproject.com/en/dev/ref/views/#serving-files-in-development
5
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}
这个函数会返回一个包含MEDIA_ROOT目录下所有图片的json对象。
需要安装django-annoying这个包;)
25
这里有一段代码给你:
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 %}