[Solved]-A Simple View to Display/Render a Static image in Django

30👍

If you need to render an image read a bit here http://www.djangobook.com/en/1.0/chapter11/ and use your version of the following code:

For django version <= 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")

For django 1.5+ mimetype was replaced by content_type(so happy I’m not working with django anymore):

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")

Also there’s a better way of doing things!

Else, if you need a efficient template engine use Jinja2

Else, if you are using Django’s templating system, from my knowledge you don’t need to define STATIC_URL as it is served to your templates by the “static” context preprocessor:

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',
)

3👍

In your last example (image5) you should use {{ STATIC_PREFIX }} instead of {% STATIC_PREFIX %}

STATIC_PREFIX is variable, not a tag

👤Igor

0👍

To avoid defining STATIC_URL explicitly, you can use a RequestContext when rendering your template. Just make sure django.core.context_processors.static is in your TEMPLATE_CONTEXT_PROCESSORS setting.

from django.template import RequestContext
...
return HttpResponse(html.render(RequestContext(request, ctx)))

Alternatively, you could use the static template tag.

html = Template('<img src="{% static "victoryDance.gif" %} alt="Hi!" />')

A third option is the get_static_prefix template tag.

Leave a comment