Home > front end >  display picutre in grid layout djang-admin
display picutre in grid layout djang-admin

Time:10-04

first, I am having issues with displaying thumbnails in Django-admin, I tried the code below but it is not working it seems,

class Pictures(models.Model):
    image = models.ImageField(null=True)
    date_added = models.DateField(auto_now_add=True)
    organization = models.ForeignKey(Organisation,on_delete=models.CASCADE)
    

    def __unicode__(self):
        return f"{self}"


    @mark_safe
    def image_img(self):
        if self.image:
            return format_html('<img src="{0}" style="width: 60px; height:65px;" />'.format(self.image.url))
        else:
            return format_html('<img src="" alt={0} style="width: 60px; height:65px;" />'.format("noimagefound"))
            
    image_img.short_description = 'Image'
    image_img.allow_tags = True



class PicturesAdmin(admin.ModelAdmin):

    list_display = ('image', 'date_added','image_img')
    autocomplete_fields = ['organization']

    list_display_links = ('date_added',)

I also want to display these thumbnails in the grid layout, how can I achieve that any simple approach

enter image description here

CodePudding user response:

I think you got the format_html part wrong

    @mark_safe
    def image_img(self):
        if self.image:
            return format_html('<img src="{}" style="width: 60px; height:65px" />', self.image.url)
        else:
            return format_html('<img src="" alt="{}" style="width: 60px; height:65px" />', "noimagefound")
            

CodePudding user response:

models.py

from django.utils.safestring import mark_safe
class Pictures(models.Model):
    image = models.ImageField(blank=True,upload_to="pictures/")
    date_added = models.DateField(auto_now_add=True)
    organization = models.ForeignKey(Organisation,on_delete=models.CASCADE)
    

    def __str__(self):
        return f"{self.pk}"


    def image_img(self):
        if self.image:
            return mark_safe('<img src="%s" style="width: 60px; height:65px;" />' % self.image.url )
        else:
            return mark_safe('<img src="" alt="%s" style="width: 60px; height:65px;" />' % "noimagefound")
            
    image_img.short_description = 'Image'
  • Related