0

I have a problem with displaying user submitted images in django. i've read through a lot of other threads similar to this question but couldn't get anything to work from those solutions.

i have a model with an image field that i submitted through the admin panel and the image uploaded correctly.

class Listing(models.Model):
    #fields editable by users
    title = models.CharField(max_length=25)
    description = models.TextField()
    starting_bid = models.DecimalField(max_digits=6, decimal_places=2)
    image_url = models.ImageField(upload_to='images/')
    #auto-created fields

    def __str__(self):
        return self.title

to settings.py i added

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

and i added the static line in my urls.py

from django.urls import path
from django.conf.urls.static import static
from django.conf import settings

from . import views

urlpatterns = [
    path("", views.index, name="index"),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

and i am trying to render in the template the image

{% for entry in entries %}

    <div class="container">
        <img src="{{entry.image_url}}", alt="image">
        <p>{{entry.image_url}}</p>
        <p>{{entry.title}}</p>
    </div>



    {% empty %}
    <p>There are no active listings right now! come back later</p>
    {% endfor %}

in my main directory with my app folders i have the 'media' folder with the 'images' folder inside. The HTML returns the objects and displays the title as expected and prints the image url as "images/file.jpg" as i would expect. but the image won't load and instead displays the alt. should the image url be "media/images/file.jpg"? whats going wrong here?

1 Answer 1

1

Wrong img link, should be

 <img src="{{ entry.image_url.url }}", alt="image">
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you!! i love/hate when the solution is so simple. works perfectly now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.