簡體   English   中英

Python圖像顯示Django

[英]Python images display Django

自從我最后一個問題在這里: 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. 我需要在視圖中創建一個def,以將列表從glob.glob饋送到此模板或類似模板。

我不知道的是:

  • 該視圖中的def必須看起來如何?

和這里:

  • 我需要寫些什么才能在瀏覽器中顯示一張圖像和聲音?
  • 我要寫什么才能顯示圖像列表和聲音?

感謝您的時間!

使用urls.py中的額外上下文創建直接指向模板的url:

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 %}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM