Song Yang
Song Yang

Reputation: 485

How to display an image inside Django Admin's detail view of a model?

I want to display an image inside a detail view of a model, when browsing through Django Admin. I have seen other posts about displaying images in the list view of all instances of a model in Django Admin. But I'm interested in seeing the image on the page where you can edit the data. What I have without the image.

models.py

class Label(models.Model):
    label = models.TextField()
    fragment = models.ForeignKey('Fragment', models.DO_NOTHING, null=True)
    in_english = models.BooleanField(default=True)

    validated = models.BooleanField(default=False)

    def __str__(self):
        return str(self.fragment)

admin.py

@admin.register(Label)
class LabelsAdmin(admin.ModelAdmin):
    fields = ("label", "in_english", "validated", )
    
    # What I tried. This is not working even after adding 'image' to the fields. I get an error.
    # def image(self, obj):
    #     return format_html('<img src="{0}" />'.format(f"/static/fragments/{obj}.png"))

Upvotes: 1

Views: 613

Answers (1)

Md Shahbaz Ahmad
Md Shahbaz Ahmad

Reputation: 1166

you create a method like display_image.

def display_image(self, obj):
    # get image url 
    image_url = '<your_image_url>'
    if image_url is not None:
        return format_html('<img src="{}">', image_url)
    return None

Add 'display_image' in fields list

fields = ("label", "in_english", "validated", 'display_image')

then make this field as a readonly

readonly_fields = ['display_image']

Upvotes: 4

Related Questions