Search code examples
pythondjangourl-patternimagefield

Image paths in Django view are relative to directory instead of MEDIA_URL


I've been struggling with this problem for a few days and unable to solve it on my own. I am working on a blog site. The post view is rendered at a URL such as this:

domain.com/blog/specificpost/

I have an ImageField in my model. The images upload properly and I can address the images at the correct URLs.

domain.com/media/asset.jpg

In my settings.py I have defined the media paths. When I access the image files from the Admin, they work properly.

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

When rendering the view of the post, the image path is rendered incorrectly in the DOM. It is:

domain.com/blog/media/asset.jpg

It should be:

domain.com/media/asset.jpg

In my urlpattern I have appended:

+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

and added the relevant imports to urls.py. I believe this code is supposed to serve the files at the domain root during development.

I have tried all the solutions here, but the image URLs still render relative to the directory. Any help to set me on the correct path would be useful, thank you very much.

Post template:

{% extends "base.html" %}

{% block journal_entry %}
    <main class="content">
        <section class="photo">
            <img src="{{ object.image }}">
        </section>
        <section class="entry">
            <section class="entry-content">
                {{ object.body|linebreaks }}
            </section>
            <section class="entry-meta">
                {{ object.created }}<span class="user-options"> • <a href="#">Delete</a></span>
            </section>
        </section>
    </main>
{% endblock %}

Solution

  • Try using {{ object.image.url }} instead of {{ object.image }} in your template.