9

我试图找到使用 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)))

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

4

3 回答 3

26

如果您需要渲染图像,请在此处阅读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',
)
于 2012-07-20T10:56:57.997 回答
3

在您的最后一个示例(image5)中,您应该使用{{ STATIC_PREFIX }}而不是{% STATIC_PREFIX %}

STATIC_PREFIX是变量,不是标签

于 2012-07-20T14:50:59.160 回答
0

为避免STATIC_URL显式定义,您可以RequestContext在呈现模板时使用 a。只要确保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模板标签。

于 2012-07-20T10:41:59.277 回答