[Django]-How do I pass an image from URL to a Django template?

3👍

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.

Leave a comment