views:

26

answers:

2

Is there a way to customize the way a field is displayed in the django admin results list? For example, I'd like to display an image based on the field value, just like boolean fields are displayed using an image rather than text value.

+1  A: 

Define a method in your admin class that returns the HTML you want.

class MyAdmin(admin.ModelAdmin):
    list_display = ('name', 'my_image_field')

    def my_image_field(self, obj)
        return '<img src="/path/to/my/image/%s"/>' % obj.url
    my_image_field.allow_tags = True
Daniel Roseman
A: 

In addition to the method that Daniel suggested, you can also define that function on your model as a property and then add it to your list_display just like a regular field:

class MyModel(models.Model):
    image_field = models.ImageField(...)

    @property
    def my_image_field(self):
        return return '<img src="%s"/>' % self.image_field.url
    my_image_field.allow_tags = True

The advantage of doing it this way is that the my_image_field property is now available from anywhere that you're working with a MyModel object, rather than just in the admin (admittedly probably not a huge use case for this specific property, but definitely comes in handy in other circumstances).

Josh Ourisman