在 django-tables2 中显示图像
Display the image in the django-tables2
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
models.py
class Product(models.Model):
name = models.CharField(max_length=250)
image = models.ImageField()
tables.py
import django_tables2 as tables
from .models import Product
class ProductTable(tables.Table):
class Meta:
model = Product
fields = ("image" ,"name")
views.py
在 views.py 中,我过滤模型对象并获得 QuerySet
import django_tables2 as tables
from .models import Product
from .tables import ProductTable
-----
table = ProductTable(new_objects) #new_objects is Product QuerySet
return render(request, 'home.html', {'table': table })
结果
我得到了 table,但没有图片,只有链接。 如何显示图片?
如果您查看文档,有一个子类化 img 列的示例。
https://django-tables2.readthedocs.io/en/latest/pages/custom-data.html#subclassing-column
from django.utils.html import format_html
class ImageColumn(tables.Column):
def render(self, value):
return format_html('<img src="/media/img/{}.jpg" />', value)
你也可以有一个自定义渲染函数:
https://django-tables2.readthedocs.io/en/latest/pages/custom-data.html#table-render-foo
def render_img_column(self, record, value):
return mark_safe(f"<img src='{record.url}' />")
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
models.py
class Product(models.Model):
name = models.CharField(max_length=250)
image = models.ImageField()
tables.py
import django_tables2 as tables
from .models import Product
class ProductTable(tables.Table):
class Meta:
model = Product
fields = ("image" ,"name")
views.py
在 views.py 中,我过滤模型对象并获得 QuerySet
import django_tables2 as tables
from .models import Product
from .tables import ProductTable
-----
table = ProductTable(new_objects) #new_objects is Product QuerySet
return render(request, 'home.html', {'table': table })
结果
我得到了 table,但没有图片,只有链接。 如何显示图片?
如果您查看文档,有一个子类化 img 列的示例。
https://django-tables2.readthedocs.io/en/latest/pages/custom-data.html#subclassing-column
from django.utils.html import format_html
class ImageColumn(tables.Column):
def render(self, value):
return format_html('<img src="/media/img/{}.jpg" />', value)
你也可以有一个自定义渲染函数:
https://django-tables2.readthedocs.io/en/latest/pages/custom-data.html#table-render-foo
def render_img_column(self, record, value):
return mark_safe(f"<img src='{record.url}' />")