[英]A Simple View to Display/Render a Static image in Django
我試圖找到使用django的模板上下文加載器顯示圖像的最有效方法。 我的應用程序中有一個靜態目錄,其中包含圖像'victoryDance.gif'和項目級別的空靜態根目錄(使用settings.py
)。 假設我的urls.py
和settings.py
文件中的路徑是正確的。 什么是最好的觀點?
from django.shortcuts import HttpResponse
from django.conf import settings
from django.template import RequestContext, Template, Context
def image1(request): # good because only the required context is rendered
html = Template('<img src="{{ STATIC_URL }}victoryDance.gif" alt="Hi!" />')
ctx = { 'STATIC_URL':settings.STATIC_URL}
return HttpResponse(html.render(Context(ctx)))
def image2(request): # good because you don't have to explicitly define STATIC_URL
html = Template('<img src="{{ STATIC_URL }}victoryDance.gif" alt="Hi!" />')
return HttpResponse(html.render(RequestContext(request)))
def image3(request): # This allows you to load STATIC_URL selectively from the template end
html = Template('{% load static %}<img src="{% static "victoryDance.gif" %}" />')
return HttpResponse(html.render(Context(request)))
def image4(request): # same pros as image3
html = Template('{% load static %} <img src="{% get_static_prefix %}victoryDance.gif" %}" />')
return HttpResponse(html.render(Context(request)))
def image5(request):
html = Template('{% load static %} {% get_static_prefix as STATIC_PREFIX %} <img src="{{ STATIC_PREFIX }}victoryDance.gif" alt="Hi!" />')
return HttpResponse(html.render(Context(request)))
謝謝你的回答這些觀點都有效!
如果您需要在http://www.djangobook.com/en/1.0/chapter11/上閱讀一些圖像,請使用以下代碼的版本:
對於django版本<= 1.5:
from django.http import HttpResponse
def my_image(request):
image_data = open("/path/to/my/image.png", "rb").read()
return HttpResponse(image_data, mimetype="image/png")
對於django 1.5+ mimetype
被content_type
取代(很高興我不再使用django了):
from django.http import HttpResponse
def my_image(request):
image_data = open("/path/to/my/image.png", "rb").read()
return HttpResponse(image_data, content_type="image/png")
還有一種更好的做事方式!
否則,如果您需要高效的模板引擎,請使用Jinja2
另外,如果你正在使用Django的模板系統,據我所知你不需要定義STATIC_URL,因為它是由“靜態”上下文預處理器提供給你的模板的:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.static',
'django.core.context_processors.media',
'django.core.context_processors.request',
'django.contrib.messages.context_processors.messages',
)
在上一個示例( image5 )中,您應該使用{{ STATIC_PREFIX }}
而不是{% STATIC_PREFIX %}
STATIC_PREFIX
是可變的,而不是標簽
為了避免定義STATIC_URL
明確,你可以用一個RequestContext
渲染你的模板時。 只需確保django.core.context_processors.static
在您的TEMPLATE_CONTEXT_PROCESSORS
設置中。
from django.template import RequestContext
...
return HttpResponse(html.render(RequestContext(request, ctx)))
或者,您可以使用靜態模板標記 。
html = Template('<img src="{% static "victoryDance.gif" %} alt="Hi!" />')
第三個選項是get_static_prefix
模板標記。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.