Django Admin 显示来自 Imagefield 的图像
虽然我可以在 list_display 中显示上传的图像,但是否可以在每个模型页面上执行此操作(如在更改模型时获得的页面中)?
While I can show an uploaded image in list_display is it possible to do this on the per model page (as in the page you get for changing a model)?
快速示例模型是:
Class Model1(models.Model):
image = models.ImageField(upload_to=directory)
默认管理员显示上传图片的网址,但不显示图片本身.
The default admin shows the url of the uploaded image but not the image itself.
谢谢!
好的.在您的模型类中添加一个方法,如:
Sure. In your model class add a method like:
def image_tag(self):
from django.utils.html import escape
return u'<img src="%s" />' % escape(<URL to the image>)
image_tag.short_description = 'Image'
image_tag.allow_tags = True
并在您的 admin.py
添加:
fields = ( 'image_tag', )
readonly_fields = ('image_tag',)
到您的 ModelAdmin
.如果您想限制编辑图像字段的能力,请务必将其添加到 exclude
属性中.
to your ModelAdmin
. If you want to restrict the ability to edit the image field, be sure to add it to the exclude
attribute.
注意:在 Django 1.8 和 'image_tag' 仅在 readonly_fields 中它没有显示.'image_tag' 只在字段中,它给出了未知字段的错误.您需要在字段和 readonly_fields 中使用它才能正确显示.
Note: With Django 1.8 and 'image_tag' only in readonly_fields it did not display. With 'image_tag' only in fields, it gave an error of unknown field. You need it both in fields and in readonly_fields in order to display correctly.