[Django]-Django ImageField Image Not Displaying

2👍

Printing the media root helped me solve this issue. Thanks Alasdair.

I don’t think there was any issue with my model field above.

The urls.py code that I ended up using is directly from Django docs for Django 2.0 in handling static files https://docs.djangoproject.com/en/2.0/howto/static-files/.

The changes I made to Settings were done thanks to printing my MEDIA_ROOT in the console. I changed the syntax and the direction of a slash (blog\media). I also deleted the context processor shown above in my TEMPLATES options.

Here’s what works for me:

models.py

thumbnail = models.ImageField(default='img/default.png', upload_to='img', blank=True, null=True)

urls.py

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

urlpatterns = [...] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py

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

print(MEDIA_ROOT)

Template tag

<img class="card-image mr-3" src="{{ post.thumbnail.url }}" alt="Generic placeholder image">

1👍

Django ImageField for Admin Panel

There is important thing you have to define your MEDIA_URL in urls.py.
Without this definition framework doesn’t gives to you permission to access image
Setting.py

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

urls.py

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

Models.py

class Product(models.Model):
    title = models.CharField(max_length=150)
    image=models.ImageField(blank=True,upload_to='images/')

    def __str__(self):
       return self.title

    def image_tag(self):
        return mark_safe('<img src="{}" height="50"/>'.format(self.image.url))
    image_tag.short_description = 'Image'

Admin.py

class ProductAdmin(admin.ModelAdmin):
list_display = ['title','image_tag']
readonly_fields = ('image_tag',)

Leave a comment