Для этого можно использовать либо
property:
import os
from django.db import models
class Article(models.Model):
title = models.CharField(
max_length=200,
)
image = models.ImageField(
blank=True,
upload_to='images',
)
@property
def thumbnail(self):
if self.image:
path, filename = os.path.split(self.image.url)
name, ext = os.path.splitext(filename)
filename = 'prefix_' + name + '_suffix' + ext
return os.path.join(path, filename)
либо функцию:
import os
from django.contrib import admin
from django.utils.html import format_html
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
list_display = (
'title',
'get_thumbnail',
)
fields = (
'title',
'get_thumbnail',
)
readonly_fields = (
'get_thumbnail',
)
def get_thumbnail(self, obj):
if obj.image:
path, filename = os.path.split(self.image.url)
name, ext = os.path.splitext(filename)
filename = 'prefix_' + name + '_suffix' + ext
return format_html('<img src="{}">', os.path.join(path, filename))
get_thumbnail.short_description = 'Thumbnail'
get_logo.admin_order_field = 'image'
либо и то, и другое:
import os
from django.contrib import admin
from django.utils.html import format_html
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
list_display = (
'title',
'get_thumbnail',
)
fields = (
'title',
'get_thumbnail',
)
readonly_fields = (
'get_thumbnail',
)
def get_thumbnail(self, obj):
url = obj.thumbnail
return format_html('<img src="{}">', url) if url else ''
get_thumbnail.short_description = 'Thumbnail'
get_logo.admin_order_field = 'image'