Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

Django: Display image in admin interface

I've defined a model which contains a link an image. Is there a way to display the image in the model items list? My model looks like this:

class Article(models.Model):
    url = models.CharField(max_length = 200, unique = True)
    title = models.CharField(max_length = 500)
    img = models.CharField(max_length = 100) # Contains path to image

    def __unicode__(self):
       return u"%s" %title

Is there a way to display the image together with title?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can create a model instance method with another name, allow HTML tags for its output and add this method as a list field. Here is an example:

First add a new method returning the HTML for the image inclusion:

class Article(models.Model):
    ...
    def admin_image(self):
        return '<img src="%s"/>' % self.img
    admin_image.allow_tags = True

Then add this method to the list:

class ArticleAdmin(admin.ModelAdmin):    
    ...
    list_display = ('url', 'title', 'admin_image')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...