在Django中显示/渲染静态图像的简单视图

Jos*_*Box 7 python django django-staticfiles django-1.4

我试图找到使用django的模板上下文加载器显示图像的最有效方法.我的应用程序中有一个静态目录,其中包含图像'victoryDance.gif'和项目级别的空静态根目录(带settings.py).假设我urls.pysettings.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)))
Run Code Online (Sandbox Code Playgroud)

谢谢你的回答这些观点都有效!

Ste*_*Nch 22

如果您需要在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")
Run Code Online (Sandbox Code Playgroud)

因为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")
Run Code Online (Sandbox Code Playgroud)

还有一种更好的做事方式!

否则,如果您需要高效的模板引擎,请使用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',
)
Run Code Online (Sandbox Code Playgroud)