开发者

Is there a way to customize how a field looks in the results list?

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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜