How to display image in django admin?

Hello, I am currently new to Django and web development and I was wondering if how can I display the image in Django admin? Currently it just shows this:

Also here are my urls, models and settings for your reference. Thank you very much in advance.

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

app_name = 'users'

#static image so that djanog can display image

urlpatterns=[
    path('',views.index, name='index')
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) +static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)
from django.db import models
from datetime import datetime
import os, random
from django.utils import timezone
#To display image correctly
from django.utils.html import mark_safe

now = timezone.now()

# Create your models here.

def image_path(instance,filename):
    basefilename, file_extension = os.path.splitext(filename)
    chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'
    randomstr = ''.join((random.choice(chars)) for x in range (10))
    _now = datetime.now()

    return 'profile_pic/{year}-{month}-{imageid}-{basename}-{randomstring}{ext}'.format(
        imageid =instance, basename = basefilename, randomstring = randomstr, ext = file_extension,
          year = _now.strftime('%Y'), month = _now.strftime('%M'), day=_now.strftime('%d'))


class User(models.Model):
    user_fname = models.CharField(max_length=200, verbose_name='First name')
    user_lname = models.CharField(max_length=200, verbose_name=' Last Name')
    user_email = models.CharField(unique=True, max_length=200, verbose_name='Email')
    user_position = models.CharField(max_length=200, verbose_name='Position')
    user_image = models.ImageField(upload_to=image_path, default='profile_pic/image.jpg')

    #To display image as an image not as an object
    def image_tag(self):
        return mark_safe('<img src="users/media/%s" width ="50" height="50"/>'%(self.user_image))
    

    pub_date = models.DateField(default=now)


    def __str__(self):
        return self.user_email

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

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

PS: This is my folder structure:)

employee
media
urls

You should use url property.

    def image_tag(self):
        return mark_safe('<img src="%s" width ="50" height="50"/>'%(self.user_image.url))
1 Like

Thanks bro, it worked