Fiona Xu
Fiona Xu

Reputation: 31

how to display images by using django-tables2

I am new to Django-tables2, and I've searched around for this but haven't had much luck so looking for a bit of help. I am trying to display images in the cells of django-tables2; however, I only have the links to the images on my page and need to click the links and open new tabs to see the images. Here's what my code looks like now:

models.py   

class Item(models.Model):
    title = models.CharField(max_length=50)
    author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True)
    collection = models.ManyToManyField(Collection)
    url = models.URLField(max_length=200, null=True)
    date = models.DateField('Date Added', default=datetime.date.today)
    item = models.ImageField(upload_to='media/img', null=True)
    tag = models.CharField(max_length=100, null=True)

    class Meta:
        ordering = ["title", "date"]

    def __str__(self):
        return self.title


tables.py

class ImageColumn(tables.Column):
    def render(self, value):
        return mark_safe('<img src="/media/img/%s" />' % escape(value))

class ItemTable(tables.Table):
    image  = ImageColumn('item')

    class Meta:
        model = Item
        fields = ('id', 'item', 'title', 'author', 'collection', 'tag', 'date')
        template_name = 'django_tables2/bootstrap.html'

And on my webpage, it shows like this: enter image description here

It seems the image column doesn't do any help, but I have no clue how to do it. Any help is much appreciated.

Upvotes: 3

Views: 2769

Answers (2)

Prashant
Prashant

Reputation: 432

This is what I did as per the answer provided by @Jieter above and it worked.

tables.py

    class ImageColumn(tables.Column):
        def render(self, value):
            return format_html(
               '<img src="{url}" class="fav" height="20px", width="20px">',
                url=value
                )
    class DataTable(tables.Table):

        fav = ImageColumn()

And in my views.py I assigned the value to the image:

views.py

    data = []
    dt = {
          "fav": "/static/images/fav.png"
          }

    data.append(dt)

    return DataTable(data)

HTH

Upvotes: 1

Jieter
Jieter

Reputation: 4229

Your approach seems good, but I think there is a small error somewhere. This is a simplified version from an actual use of django-tables2 with images:

from django.utils.html import format_html

class ImageColumn(tables.Column):
    def render(self, value):
        return format_html(
            '<img src="{url}" height="50px", width="50px">',
            url=value
        )

If it still doesn't work, inspect the HTML generated (context menu -> view source in your browser).

Upvotes: 2

Related Questions