python - Django Admin 显示来自 Imagefield 的图像

标签 python django django-models django-admin admin

虽然我可以在 list_display 中显示上传的图像,但是否可以在每个模型页面上执行此操作(就像在更改模型时获得的页面中一样)?

一个快速示例模型是:

Class Model1(models.Model):
    image = models.ImageField(upload_to=directory)

默认管理员显示上传图片的 url,而不是图片本身。

谢谢!

最佳答案

当然。在您的模型类中添加一个方法,例如:

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 属性中。

注意:对于 Django 1.8 和仅在 readonly_fields 中的“image_tag”,它不会显示。仅在字段中使用“image_tag”,它给出了未知字段的错误。您在 fields 和 readonly_fields 中都需要它才能正确显示。

关于python - Django Admin 显示来自 Imagefield 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16307307/

相关文章:

python - 求二项式系数模质数,面试街头挑战

python - 对齐的 LaTeX 方程 SymPy

sql - django:datediff sql 查询?

python - 单击按钮后获取表格 BeautifulSoup Python

python - Django 内部服务器 500 错误 AWS Elastic-Beanstalk 问题

python - 当搜索和结果位于同一页面时分页

python - Django 设置 LOGOUT_REDIRECT_URL 不起作用

Django : Unable to import model from another App

django - "QuerySet' 对象没有属性 'user'

Django 管理员 : change displayed column name in inline ManyToMany field