Search code examples
pythondjango

Django templates: model.image.url gets relative url, how to get full domain url?


I'm new to Django and I've been trying to get my images to show on a site I'm building.

On my templates I use <img src="{{ model.image.url }}" /> and I get the MEDIA_URL + IMAGE_PATH.

Something like this: upload/gallery/zips/thumbnails/zips.png. upload/ is my MEDIA_URL.

How can I get my url to look something like: http://127.0.0.1:8000/upload/gallery/zips/thumbnails/zips.png without having to append it like this: <img src="http://127.0.0.1:8000/{{ gallery.thumbnail.url }}" />?

So sorry if this is the stupidest question ever asked on SO.


Solution

  • You can prepend your media url using the request object:

    <img src="{{ request.get_host }}{{ model.image.url }}" />
    

    *Note - you'll want to make sure you have request in your template context processors:

    'django.template.context_processors.request'