Django管理员从Imagefield显示图像 [英] Django Admin Show Image from Imagefield

查看:68
本文介绍了Django管理员从Imagefield显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我可以在list_display中显示上传的图像,但是可以在每个模型页面上进行此操作(如您在更改模型时所使用的页面)?



一个快速的样本模型是:

 类Model1(模型.Model):
image = models.ImageField(upload_to = directory)

默认管理员显示上传图片的网址,但不显示图片本身。



谢谢!

解决方案

不确定。在您的模型类中,添加一个方法,如:

  def image_tag(self):
return u'< img src =%s/>'%< URL到图像>
image_tag.short_description ='Image'
image_tag.allow_tags = True

admin.py add:

  fields =('image_tag' ,)
readonly_fields =('image_tag',)

到你的的ModelAdmin 。如果要限制编辑图像字段的功能,请确保将其添加到 exclude 属性。



注意:只有在readonly_fields中没有显示Django 1.8和'image_tag'。只有在字段中使用'image_tag',就会出现未知字段的错误。您需要在字段和readonly_fields中才能正确显示。


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)?

A quick sample model would be:

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.

Thanks!

解决方案

Sure. In your model class add a method like:

def image_tag(self):
    return u'<img src="%s" />' % <URL to the image>
image_tag.short_description = 'Image'
image_tag.allow_tags = True

and in your admin.py add:

fields = ( 'image_tag', )
readonly_fields = ('image_tag',)

to your ModelAdmin. If you want to restrict the ability to edit the image field, be sure to add it to the exclude attribute.

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.

这篇关于Django管理员从Imagefield显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆