Ad

Django Image Should Be Displayed But Isnt

- 1 answer

I don't understand why the image isn't being displayed,

HTML

 <div class="features-icons-item mx-auto mb-5 mb-lg-0 mb-lg-3">
     <div class="features-icons-icon d-flex">
         <img src="{{ x.pic.url }}">
     </div>

model

class Item(models.Model):
title = models.CharField(max_length=200, default='item name...')
desc = models.TextField(default='Description....')
pic = models.ImageField(default='default.png', upload_to='item_pics')

views

def index(request):
itemList = Item.objects.all()
return render(request, 'main/items.html', {'itemlist': itemList})

settings

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

Answer

I think you have not added the media url in urlpatterns.

Change the url.py in project as follows:

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

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Refer the django documentation for more Explanations Django media files

Ad
source: stackoverflow.com
Ad