Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show image in django admin

Tags:

python

django

This question was already asked ,but that was not solving my problem.i have searched a lot but i am unable to show the images as thumbnail in admin panel.

MY models.py is

thumb_impression=models.ImageField(blank=True, null=True)
cust_pic=models.ImageField(blank=True, null=True ,)

def admin_thumbnail(self):
    return mark_safe(u'<img src="%s" />' % (self.cust_pic))

admin_thumbnail.short_description = 'Thumbnail'
# admin_thumbnail.allow_tags = True

admin_thumbnail = property(admin_thumbnail)

Admin.py is

class AccountAdmin(admin.ModelAdmin):

readonly_fields =  ('balance','terms_and_condition')

fieldsets =  [
    ('Account Details',{
        'fields':['cust_id','cust_first_name','cust_middle_name','cust_last_name','cust_pic']
    }),
    ('Thumbnail',{
        'fields':['cust_pic']
    }),
]

list_display = (
    'cust_first_name',

    'cust_last_name',
    'admin_thumbnail',
)

admin.site.register(Account,AccountAdmin)

urls.py is

urlpatterns=[
url(r'^',include(router.urls)),

url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),

]

I tried previous solution but i am unable to find the correct answer.please help me to find out the solution.please give me a proper example so that i can apply it. Thanks in advance

like image 876
C P Verma Avatar asked Oct 12 '15 07:10

C P Verma


2 Answers

The proper definition as explained by the documentation

class FooAdmin(admin.ModelAdmin):
    list_display = ('bar',)

    def bar(self, obj):  # receives the instance as an argument
        return '<img src="{thumb}" />'.format(
            thumb=obj.image.url,
        )
    bar.allow_tags = True
    bar.short_description = 'sometext'


admin.site.register(Foo, FooAdmin)

Obviously don't add the property to readonly_fields

like image 41
Hedde van der Heide Avatar answered Oct 01 '22 14:10

Hedde van der Heide


def admin_thumbnail(self):
    return u'<img src="%s" />' % (self.image.url)
admin_thumbnail.short_description = 'Thumbnail'
admin_thumbnail.allow_tags = True

The list_display bit looks identical too, and I know that works. The only thing that looks suspect to me is your indentation - the two lines beginning image_img at the end of your models.py code should be level with def image_img(self):, like this:

def image_img(self):
    if self.image:
        return u'<img src="%s" />' % self.image.url_125x125
    else:
        return '(Sin imagen)'
image_img.short_description = 'Thumb'
image_img.allow_tags = True
like image 84
Cp Verma Avatar answered Oct 01 '22 13:10

Cp Verma