我想找到使用django的模板上下文加載器顯示圖像的最有效方法。我的應用程序中有一個靜態目錄,其中包含圖像'victoryDance.gif'和一個空的靜態根目錄(項目級別爲settings.py
)。假設我的urls.py
和settings.py
文件中的路徑是正確的。什麼是最好的看法?一個簡單的視圖來顯示/渲染Django中的靜態圖像
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)))
感謝您的回答這些視圖都可以工作!
用'content_type'替換'mimetype'從django 1.5 – 2015-06-13 02:29:15