最近遇到一个需求, 需要在django 的 admin 编辑页内展示由用户上传的进行反馈的图片, 还要支持点击查看原图, 所以需要在编辑页内自定义 img 标签及 a 标签进行图片的展示及点击跳转

 

import json

from django.contrib import admin
from django.utils.safestring import mark_safe

from yourapp.models import YourModel


@admin.register(YourModel)  # 注册模型到admin站点中
class YourAdmin(admin.ModelAdmin):
    
    ...

    # 自定义一个字段
    def image_url(self, obj):
        image = obj.image
        if fb_img:
            image_html = ""
            for img_url in json.loads(image):
                artwork = ".".join(img_url.split(".")[0:-2])
                # 根据业务需求, 拿到所有图片的url, 拼接 img 及 a 标签
                image_html += '<a href="{}" target="_blank"><img src="{}" style="width:200px; height:200px; margin-right:2.5px; margin-left:2.5px; margin-bottom:5px"/></a>'.format(artwork, img_url)
            html = "<div>" + image_html + "</div><div>提示: 点击图片查看原图</div>"
        else:
            html = "-"
        return mark_safe(html)  # 取消转义
    image_url.short_description = "反馈图片"
    image_url.allow_tags = True
    
    # 重写编辑页, 继承父类方法
    def change_view(self, request, object_id, extra_context=None):
        self.fields = ("name", "created", "content", "image_url")  # 将自定义的字段注册到编辑页中
        self.readonly_fields = ("name", "created", "image_url")  # 务必将该字段设置为仅限可读, 否则抛出异常
        return super(YourAdmin, self).change_view(request, object_id, extra_context=extra_context)