Home > Back-end >  How do I pass an image from URL to a Django template?
How do I pass an image from URL to a Django template?

Time:11-11

I have the following view:

import requests

def home(request):
    r = requests.get("https://via.placeholder.com/150")

    # Use the headers (r.headers) for something here
    ...

    return render(request, 'index.html', {'image': r.content})

And then in template, I want to use the image in an <img> tag, like so:

<img src="{{ image }}">

Unfortunately, the image is broken in the template. When printing r.content, I get the following:

>>> r.content
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x96\x00\x00\x00\x96\x04\x03\x00\x00\x00\xce/l\xd1\x00\x00\x00\x1bPLTE\xcc\xcc\xcc\x96\x96\x96\xaa\xaa\xaa\xb7\xb7\xb7\xc5\xc5\xc5\xbe\xbe\xbe\xb1\xb1\xb1\xa3\xa3\xa3\x9c\x9c\x9c\x8b*p\xc6\x00\x00\x00\tpHYs\x00\x00\x0e\xc4\x00\x00\x0e\xc4\x01\x95 \x0e\x1b\x00\x00\x01\x00IDATh\x81\xed\xd21o\x830\x18\x84\xe1\x8b1&\xa3\t\xb4s\x93!3\xde:\xc2\xd0\x9d\xaa\x1d\x18\x89\x84P\xc6D\x91\x98QR\xa9\xfd\xd9\xfd\x0ci;\x9b\xb5\xf7\x8c\x87\xf4\x06\x1c\x03DDDDDDDDDD\xb4\x82I\xd3\x16\xc7\xdb\xdfd\xa7\xc9|\x15\xa1\xad-\xd4\xd0\xd7\xd1\xe3\xa1\xfcY\x94\x9d&\xd7\xe7\x81)\x97"\x91\xdfOZ\xd5\xc2\xe4:\x03\xa2\xd4N\xd3\x80}`\xeb\xc5!y\x97/-\xa3\x11\xb8\xaa\x13\xa0\xdf\xec4\xe5x\x0el\xa1\xc2\xea\xbcAU\xc6\xd2r\xae\x96E[?\xe9\x1c\xcd\x82V\xd7\xb4\x95/ \xd9\xe0\xde\xea\x9a\xce\xca\xa3\xe0\x96\x1c\xd18\xbf\x97\xc9\xee-\x99>\x16\xbd\x17\x10\xdb\xf9\xbc\xd6\x9f\xbf\xad\xd8.:/\x07s\x92\xff\xf1\t8\xbe\x16s\xcbO\x03v\xe1\xad\xf5\xe5P\xc8\xfd\xaa\xa135\xce-?\xb9\xfe!\xbc\x15\x9f\xe5\xce\xfb{\xafF\x7f\xbf|\xcbO\x0b\xee=\x11\x11\x11\x11\x11\x11\x11\x11\x11\xfd?\xdfY\xa5%Q\x8a\xf0\x7f\xae\x00\x00\x00\x00IEND\xaeB`\x82'

What do I need to do to format the content to be usable in my template? Thanks for any help!

Edit

I know the URL can be used in the <img> tag directly. However, I need a specific header from the URL in my Python code, so this way, I can save one extra request.

CodePudding user response:

You can pass the URL itself as src="…" of the image, so:

<img src="https://via.placeholder.com/150">

another option is to use base64 encoding and thus encode this with:

from base64 import b64encode
import requests

def home(request):
    r = requests.get("https://via.placeholder.com/150")
    return render(request, 'index.html', {'image': b64encode(r.content).decode()})

and then render this in the template with:

<img src="data:image/png;base64,{{ image }}">

the MIME type (here image/png) might be different depending on the image format used by the server where you make the request.

  • Related