Harry Whitnear
Harry Whitnear

Reputation: 189

Django media files not found

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?

Upvotes: 0

Views: 1026

Answers (1)

Ceetified_karma
Ceetified_karma

Reputation: 368

Wrong img link, should be

 <img src="{{ entry.image_url.url }}", alt="image">

Upvotes: 1

Related Questions