django show image in admin page

Step 1: Import necessary modules in the models.py file.

from django.db import models

Step 2: Define a model with an ImageField.

class YourModelName(models.Model):
    image = models.ImageField(upload_to='path/to/upload/folder/')

Step 3: Run migrations to apply changes to the database.

python manage.py makemigrations
python manage.py migrate

Step 4: Install Pillow, a Python Imaging Library, to handle image-related tasks.

pip install Pillow

Step 5: Configure your project's settings.py file to use the media files during development.

# settings.py

import os

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

Step 6: In your app's admin.py file, import the necessary modules and create a custom admin class.

from django.contrib import admin
from .models import YourModelName

class YourModelNameAdmin(admin.ModelAdmin):
    list_display = ('id', 'display_image')

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

admin.site.register(YourModelName, YourModelNameAdmin)

Step 7: Ensure that django.contrib.admin and your app are included in the INSTALLED_APPS list in settings.py.

# settings.py

INSTALLED_APPS = [
    # ...
    'django.contrib.admin',
    'your_app_name',
    # ...
]

Step 8: Collect static files to ensure that the admin can serve media files.

python manage.py collectstatic

Step 9: Run your Django development server.

python manage.py runserver

Now, when you navigate to your admin page and view the model that includes the image field, you should see a preview of the image in the list view.