Django media image file is not displaying in template

456 Views Asked by At

I have a problem with media files in Django 4.0.4, here are the code and some screenshots to understand the problem :

Settings.py

STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'

MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'

urls.py

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

models.py

photo = models.ImageField()

index.html

{% load static %}
<h1>{{ object.title }}</h1>
<p>{{ object.description }}</p>
<p>link: {{ object.link }}</p>
<p>Category: {{ object.category }}</p>
<p>Date: {{ object.date_time|date }} at {{ object.date_time|time }}</p>

{% for photo in photo_list %}
  {{photo.photo.url}}
  <img scr="{{ photo.photo.url }}" width="250" height="250">
{% endfor %}

Image not displayed

If I copy the img src URL, e.g. http://127.0.0.1:8000/media/canvas_gb9uMM8.png, the image is well displayed.

Thank you for your help.

1

There are 1 best solutions below

4
On

If you can't use ImageField it mean you 'photo' in photo = models.FileField(). Don't had any data(image). That mean even you call it, it will display not thing. Because the photo field don't had anything to display.