Django is not displaying image

Question:

I am trying to build an e-commerce website using python’s Django framework as part of a practice project. However, I am not being able to display my product’s image on my landing page.

Django version: 3.2.4

models.py:

class Listing(models.Model):
    title = models.CharField(max_length=100)
    price = models.FloatField()
    description = models.TextField()
    image = models.ImageField(upload_to="auctions/images/", default="")

settings.py:

STATIC_URL = '/static/'

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

urls.py:

from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include("auctions.urls"))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

views.py

def index(request):
    listings = Listing.objects.all()
    return render(request, 'auctions/index.html', {
        "listings": listings
    })

index.html

{% extends "auctions/layout.html" %}
{% load static %}

{% block body %}
    <h2>Active Listings</h2>

    {% for listing in listings %}
    <div class="card" style="width: 18rem;">
        <img class="card-img-top" src="{% static listing.image %}" alt="Card image cap">
        <div class="card-body">
            <h5 class="card-title">{{ listing.title }}</h5>
            <p class="card-text">{{ listing.description }}</p>
            <p class="card-text">Price - {{ listing.price }}</p>
            <a href="#" class="btn btn-primary">Bid</a>
        </div>
    </div>
    {% endfor %}
{% endblock %}

I am only getting the alt attribute for the img tag.

Asked By: Zaid Azim

||

Answers:

As mentioned by @Pruthvi Barot you need to change the code you are using in your html from

src="{% static listing.image %}" 

to

src="{% url listing.image.url %}"

That is because you image as a media and allowing them to served via a url as you define here:

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

The static file are in this case images that you placed in the directory and do not manage (upload and delete) from the Django Admin Panel.

another solution mentioned by @MojixCoder is to replace the above mention line of code with

src="{{ listing.image.url }}"

This is the preferred solution and is the one specified in Djangos official documentation on MEDIA_URL (version 3.2)

Answered By: Chris
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.