Django 中的 Python 图像显示

0 投票
1 回答
803 浏览
提问于 2025-04-16 01:10

自从我在这里问了上一个问题:Python图像显示

我明白了,从我得到的所有答案中,glob.glob可能是我需要的唯一方向。

不过我现在卡住的地方是:

我可以通过使用glob.glob来创建一个包含我媒体目录中所有文件名的列表:

all = glob.glob("/Path_to_MEDIA/*/*.jpg")

但是我该如何利用这个列表,创建一个非常简单的图像显示,只有一个“下一步”按钮,可以调用我MEDIA_ROOT中的文件并显示它们呢?

我知道的是:

  1. 我有一个模板,看起来有点像默认的目录索引:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
      <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta http-equiv="Content-Language" content="en-us" />
        <meta name="robots" content="NONE,NOARCHIVE" />
        <title>Index of {{ directory }}</title>
      </head>
      <body>
        <h1>Index of {{ directory }}</h1>
        <ul>
          {% ifnotequal directory "/" %}
          <li><a href="../">../</a></li>
          {% endifnotequal %}
          {% for f in file_list %}
          <li><a href="{{ f|urlencode }}">{{ f }}</a></li>
          {% endfor %}
        </ul>
      </body>
    </html>
    
  2. 我需要在我的视图中创建一个函数,把glob.glob得到的列表传递给这个或类似的模板。

我不知道的是:

  • 这个视图中的函数应该怎么写?

还有:

  • 我需要写什么才能在浏览器中显示一张图片或声音?
  • 我需要写什么才能显示一系列的图片或声音?

谢谢你的时间!

1 个回答

0

在urls.py中创建一个直接指向模板的链接,并添加额外的上下文:

from django.views.generic.simple import direct_to_template
...
url(r'^whatever', direct_to_template, 
                 { 'template':'foo.html', 'extra_context': {'files':myfiles} }
                 name='whatever' ),

这里的myfiles是你文件的列表或元组。不过,要确保你的文件列表是基于MEDIA_URL来格式化的,而不是MEDIA_PATH。例如:

myfiles = [ 'relative/path/foo.jpg', 
            'http://static.mysite.com/absolute/path/bar.jpg' ]

当然,这个列表是从你的文件系统生成的,而不是写死的。你也可以在视图中处理这些文件,而不是直接指向模板——只要确保把文件的键值对放入你的上下文中:

def myview( request ... ):
  context = RequestContext(request)
  context[files]=myfiles
  return render_to_respone( ..., context_instance=context )

然后,在你的模板foo.html中:

{% for file in files %}
  <img src='YOUR_MEDIA_URL_HERE/{{ file }}' />
{% endfor %}

撰写回答