在列表中显示ImageField的图片预览
编辑应用的models.py,添加下面代码:
class Product(models.Model):
# ...
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
def image_data(self):
if self.image:
return format_html(
'<img src="/media/{}" width="100px" >',
self.image,
)
else:
return format_html(
'<img src="/static/shop/no_image.png" width="100px" >'
)
如果图片无法正常显示,请检查关于media和static相关配置
项目setting.py
STATIC_URL = "static/"
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
项目urls.py
urlpatterns = [
#...
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
在编辑页面预览图片
使用readonly_field添加image_data字段
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_display = ['name','slug','price','available','created','updated','image_data']
list_filter = ['available','created','updated']
list_editable = ['price','available']
prepopulated_fields = {'slug':('name',)}
readonly_fields = ('image_data',)
关于shop应用更多信息,请查看
Django初创shop应用-CSDN博客
Django使用session管理购物车-CSDN博客
Django创建订单-CSDN博客