2

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 %}
Charlie Deets
  • 109
  • 1
  • 11

1 Answers1

4

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

MrName
  • 2,363
  • 17
  • 31
  • This worked perfectly. Didn't realize that you had to be specific with the output of the ImageField. I knew it was going to be a simple mistake, just couldn't put my head around what I was missing. I appreciate the help, thanks a lot. – Charlie Deets Nov 14 '17 at 02:36
  • 1
    No worries, I think what happens when you reference the field itself (instead of the URL attribute) is that it uses the `__str__` method of the class, which is a relative URI, as opposed to the `url` field, which is a full URL. – MrName Nov 14 '17 at 16:09