回到顶部

Contents

Django Admin Show Image from Imagefield(Django admin 图片预览)

在 Django 管理后台中,图片字段(ImageField)默认是显示路径,期望能看到图片预览图。

编写 ImageWidgetAdmin

继承 admin.ModelAdmin, 编写自己的 image admin

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
@author: yinzhuoqun
@site: http://xieboke.net/
@email: yin@zhuoqun.info
@time: 2020/4/15 11:13
"""

from django.contrib.admin.widgets import AdminFileWidget
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
from django.contrib import admin


class AdminImageWidget(AdminFileWidget):
    # django 2.2
    # def render(self, name, value, attrs=None, renderer=None):
    #     """Render the widget as an HTML string."""
    #     context = self.get_context(name, value, attrs)
    #     return self._render(self.template_name, context, renderer)

    # def render(self, name, value, attrs=None):  # django 1.11
    def render(self, name, value, attrs=None, renderer=None):  # django 2.2
        output = []
        if value and getattr(value, "url", None):
            image_url = value.url
            file_name = str(value)
            # output.append(u' <a href="%s" target="_blank"><img src="%s" alt="%s" /></a> %s ' % \
            #               (image_url, image_url, file_name, _('Change:')))
            output.append(u' <a href="%s" target="_blank"><img src="%s" alt="%s" /></a>' % \
                          (image_url, image_url, file_name))
        output.append(super(AdminFileWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))


class ImageWidgetAdmin(admin.ModelAdmin):
    image_fields = []

    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name in self.image_fields:
            request = kwargs.pop("request", None)
            kwargs['widget'] = AdminImageWidget
            return db_field.formfield(**kwargs)
        return super(ImageWidgetAdmin, self).formfield_for_dbfield(db_field, **kwargs)

使用 ImageWidgetAdmin

# models.py
class AD(models.Model):
    """
    广告内容
    """
    title = models.CharField(verbose_name="标题", max_length=250, unique=True)
    cover = models.ImageField(verbose_name="封面", max_length=250, upload_to="ad/", blank=True, null=True)

# admins.py, ImageWidgetAdmin
class IndividualBirdAdmin(ImageWidgetAdmin):
    image_fields = ['cover', ]  # 图片预览的字段名

图片预览效果

来源 / 出处

https://stackoverflow.com/questions/16307307/django-admin-show-image-from-imagefield#

^_^
请喝咖啡 ×

文章部分资料可能来源于网络,如有侵权请告知删除。谢谢!
前一篇: django2.2 反向解析 admin 的 url
下一篇: pycharm2019.2 专业版 导入及配置已存在的 Django 项目
captcha