среда, 8 октября 2014 г.

Django. Show dynamic (not static) image as part of the template

There is plenty of imformation about how to show static image in a Django template. However, when I needed to show a generated image, which I don't want to store in a static folder, it turned out not to be so obvious.
Here  you can found some relative information.

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

But HttpResponse doesn't create a full html page, it just displays an image. So you have to do some extra work. You should define an image in the template with source that calls the view like my_image in the example above.

showgenerated.html
1:  <head>  
2:    <title>My Favourite Picture</title>  
3:  </head>  
4:  <body>  
5:  <img src="my_image" />  
6:  </body>  
7:  </html>  

urls.py
urlpatterns = patterns('',
    url(r'^my_image$', views.my_image),
)

Of course there is an obvious minus of such a method. You contact with the server twice: first to show the template and second to show the image.

Also pay attention to the content_type parameter in HttpResponse. Since Django 1.7 there is no parameter mime_type. It will cause an error.

0 коммент.:

Отправить комментарий