如何在django管理员字段中添加自定义html?

时间:2014-10-05 20:36:10

标签: django django-admin

基本上,我想要实现的是在我在添加或编辑界面中选择文件后,有一个显示图像缩略图的媒体表单。我尝试使用此代码,但它在此错误中返回。

Unknown field(s) (admin_image) specified for ImageMedia. 
Check fields/fieldsets/exclude attributes of class ImageMediaAdmin.

这是模型类:

class ImageMedia(models.Model):
    caption = models.CharField(max_length=64)
    picture = models.ImageField(upload_to='image_media', blank=True)

    def admin_image(self):
        return '<img src="%s" height="300px"/>' % self.picture
    admin_image.allow_tags = True

    def __str__(self):
        return self.caption

这是管理类

class ImageMediaAdmin(admin.ModelAdmin):
    list_display = ('caption', 'picture', 'admin_image')
    search_fields = ('caption', 'picture')
    fields = ('caption', 'picture', 'admin_image')

admin.site.register(ImageMedia, ImageMediaAdmin)

1 个答案:

答案 0 :(得分:1)

您需要更改ImageMediaAdmin以将admin_image指定为readonly_field

class ImageMediaAdmin(admin.ModelAdmin):
    list_display = ('caption', 'picture', 'admin_image')
    search_fields = ('caption', 'picture')
    fields = ('caption', 'picture', 'admin_image')
    readonly_fields = ['admin_image']