在Django Admin中显示图像缩略图而不是图像路径

时间:2015-11-21 18:07:03

标签: python django

有点新手问题,但如何在默认的Django管理员中显示图像的缩略图而不是显示图像的路径?这是我到目前为止所拥有的:

Models.py

from django.db import models


class Project(models.Model):
    name = models.CharField(max_length=200)
    description = models.CharField(max_length=500)
    thumbnail = models.ImageField(upload_to="media")

    def __str__(self):
        return self.name

class Image(models.Model):
    project = models.ForeignKey(Project)
    title = models.CharField(max_length=200)
    image = models.ImageField(upload_to="media")
    pub_date = models.DateTimeField('date published')

    def admin_thumbnail(self):
        return u'<img src="%s" />' % (self.image.url)
    admin_thumbnail.short_description = 'Thumbnail'
    admin_thumbnail.allow_tags = True

Admin.py

from .models import Project, Image

class ImageInline(admin.TabularInline):
    model = Image
    extra = 0

class ImageAdmin(admin.ModelAdmin):
    fieldsets = [
        (None,               {'fields': ['project']}),
        (None,               {'fields': ['title']}),
        (None,               {'fields': ['image']}),
        ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
    ]

class ProjectAdmin(admin.ModelAdmin):
    fieldsets = [
        (None,               {'fields': ['name']}),
        (None,               {'fields': ['thumbnail']}),
    ]
    inlines = [ImageInline]
    search_fields = ["name"]


admin.site.register(Project, ProjectAdmin)
admin.site.register(Image, ImageAdmin)

我不知道是否有更简单的方法可以做到这一点,但无论答案是否有效。谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用此方法,在具有图像的模型中添加此方法:

def image_tag(self):
    if self.thumbnail:
        return u'<img src="%s" style="width: 150px;" />' % self.thumbnail.url
    else:
        return 'No Image Found'

然后在admin.py中调用它:

list_display = ('image_tag', ...)

关于OOP,您可以创建父模型并扩展其他具有父级图像的模型,然后在父类上定义此方法