Reputation: 469
I am trying to add thumbnails to list view in django admin.
This is my admin.py for my app, i got this far:
from django.contrib import admin
from .models import Image
from django import forms
from django.db import models
class ImageAdmin(admin.ModelAdmin):
list_display = ("label","tag","order",'Edit','image_img')
list_editable= ("order",)
list_filter = ('tag',)
search_fields = ('tag', 'label')
ordering = ['-order']
list_display_links = ('Edit', )
def Edit(self, obj):
return "Edit"
def image_img(self,obj):
if obj.pic:
return '<img src="%s" height="100px"/>' % obj.pic.url
else:
return 'No_image'
image_img.short_description = 'Image'
image_img.allow_tags = True
admin.site.register(Image,ImageAdmin)
My object for picture is called "pic". If I simply add it to list view django returns link with full path. I was looking for template for list view so that I can add |safe filter but I couldn't find it. Any other idea how to achieve it?
Upvotes: 2
Views: 1398
Reputation: 12571
If you're using Django > 2.0, you can mark the routine as safe using the mark_safe()
decorator:
from django.utils.safestring import mark_safe
@mark_safe
def image_img(self,obj):
if obj.pic:
return '<img src="%s" height="100px"/>' % obj.pic.url
else:
return 'No_image'
It can also be used as a function:
def image_img(self,obj):
if obj.pic:
return mark_safe('<img src="%s" height="100px"/>' % obj.pic.url)
else:
return 'No_image'
In older versions of Django, I believe you can just set the allow_tags
option to true:
image_img.allow_tags = True # Put this after the function definition
Upvotes: 4