Search code examples
pythondjangoimagepython-imaging-library

How can I pass an image to a template in Django?


Suppose that the corresponding function in views.py looks like

from PIL import Image
def get_img(request, img_source)
    base_image = Image.open(os.getcwd() + '/deskprod/media/img/'+ img_source + ".png")
    #Some editing of base_image done with PIL that prevents image from being directly loaded in html
    return render_to_response('get_img.html', {
        'base_image': base_image},
        context_instance=RequestContext(request))

How can I then display base_image in the get_img.html template?


Solution

  • You should process the image, save it on local disk and then send a path to it or more like the media url which will correspond to that image as context to html template. You need to configure your django server to serve static and media files to do that and configure serving those files in production environment as well. Read more here https://docs.djangoproject.com/en/1.9/howto/static-files/ django-4.2

    However it should be possible to create dynamic image and serve with django in the fly with PIL if you can't or really do not want to save it locally. It will be sth like at the and of you code you should add.

    response = HttpResponse(mimetype="image/png")
    base_image.save(response, "PNG")
    return response
    

    Check also more info http://effbot.org/zone/django-pil.htm, it may work, although I didn't test it.