gpt4 book ai didi

python - 如何在 Django 管理界面中显示 BinaryField 图像预览?

转载 作者:行者123 更新时间:2023-12-04 01:37:08 24 4
gpt4 key购买 nike

我有一个带有 Django 后端的 Web 项目,为此我决定将图像存储为 BinaryField,这对我来说似乎更方便进行备份和恢复。

首先我创建了模型:

class ThermalSource(ClusterUnit):
...
scheme_image = models.BinaryField(verbose_name='Scheme', blank=True, null=True, editable=True)
...

然后创建序列化程序以在 View 集中使用(我知道它与管理界面无关,但也许会有用):

class Base64BinaryField(serializers.Field):

def to_representation(self, value):
from base64 import b64encode
return b64encode(value)

def to_internal_value(self, data):
from base64 import b64decode
return b64decode(data)


class ThermalSourceSerializer(APAMModelSerializer):
...
scheme_image_base64 = Base64BinaryField(source='scheme_image')
...

现在我可以通过 Django REST Framework 获取和设置正确转换为 Base64 的图像。

ThermalSource 的管理类现在看起来是这样的:

class ThermalSourceForm(forms.ModelForm):

scheme_image = forms.FileField(required=False)

def save(self, commit=True):
if self.cleaned_data.get('scheme_image') is not None \
and hasattr(self.cleaned_data['scheme_image'], 'file'):
data = self.cleaned_data['scheme_image'].file.read()
self.instance.scheme_image = data
return self.instance

def save_m2m(self):
# FIXME: this function is required by ModelAdmin, otherwise save process will fail
pass

class ThermalSourceAdmin(admin.ModelAdmin):
form = ThermalSourceForm
readonly_fields = ('id', )
list_display = ('id', ... 'scheme_image')

但是当我打开Django管理界面时,我只能下载文件到scheme image字段,没有配置预览。

谁能建议我如何为我的模型配置管理类,以便能够在 Django 管理界面中查看图像预览?

最佳答案

首先,将下面的代码添加到您的模型中。

def scheme_image_tag(self):
from base64 import b64encode
return mark_safe('<img src = "data: image/png; base64, {}" width="200" height="100">'.format(
b64encode(self.scheme_image).decode('utf8')
))

scheme_image_tag.short_description = 'Image'
scheme_image_tag.allow_tags = True

然后,您可以在您的 list_display (admin) 上呈现此字段。

list_display = (...'scheme_image_tag')

如@DmitriyVinokurov 所述,您可以将此标记添加到 readonly_fields

readonly_fields = (..., 'scheme_image_tag')

附言这answer解释了为什么我使用 decode('utf8')

关于python - 如何在 Django 管理界面中显示 BinaryField 图像预览?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59124008/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com