python - 如何使用 django-tables2 显示图像

标签 python django django-models django-tables2

我是 Django-tables2 的新手,我已经四处搜索过,但运气不佳,因此寻求一些帮助。我正在尝试在 django-tables2 的单元格中显示图像;但是,我的页面上只有图像的链接,需要单击链接并打开新选项卡才能查看图像。这是我的代码现在的样子:

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'

在我的网页上,它显示如下: enter image description here

图像列似乎没有任何帮助,但我不知道该怎么做。非常感谢任何帮助。

最佳答案

你的方法看起来不错,但我认为某处有一个小错误。这是 django-tables2 实际使用图像的简化版本:

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
        )

如果仍然不起作用,请检查生成的 HTML(上下文菜单 -> 在浏览器中查看源代码)。

关于python - 如何使用 django-tables2 显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50702922/

相关文章:

python - Tensorflow:确定预训练 CNN 模型的输出步幅

python requests.text 到 pandas 数据框

django - 在 url 中发送多个参数作为 Django 中的 GET 请求?

python - django-reversion 与模型 clean 方法冲突

django - 如何在 django 中使用 django-taggit 按标签过滤帖子

Django:从本地开发推送时,SQLite 覆盖 Heroku 上的 POSTGRESQL 数据库

python - 如何限制对 write 函数的 curl 调用次数?

python - Matplotlib:无法保存 PDF 图

django - 如何覆盖默认的 django 忘记密码模板?

python - MultipleChoiceField 未在 Django Admin 中显示存储的值