【问题标题】:Django Admin: Store and display Images in Postgres Binary field (By obligation)Django Admin:在 Postgres 二进制字段中存储和显示图像(按义务)
【发布时间】:2015-03-23 10:53:15
【问题描述】:

我有一个 pos 程序的后台小项目。实际上图像存储在二进制字段中,所以我必须使用它们。 例如,我有一个类别表的以下模型: 模型.py

class Categories(models.Model):
    id = models.CharField(primary_key=True, max_length=20, default=createid())
    name = models.CharField(unique=True, max_length=50)
    parentid = models.ForeignKey('self', db_column='parentid', blank=True, null=True)

    image = models.ImageField(upload_to="images", null=True)
    def __unicode__(self):              # __unicode__ on Python 2
        return '('+self.id+')'+self.name
    def save(self, *args, **kwargs):
        try:
            path1 = safe_join(os.path.abspath(settings.MEDIA_ROOT)+'\images', self.image)
            image_file = open(path1,'rb')
            file_content = image_file.read()

            self.image=file_content
        except:
            filename = 'no_image.png'
            path = safe_join(os.path.abspath(settings.MEDIA_ROOT), filename)
            #if not os.path.exists(path):
            #    raise ObjectDoesNotExist
            no_image = open(path, 'rb')
            file_content = no_image.read()
        super(Categories, self).save(*args, **kwargs)
    def image_thumb(self):
        if self.image:
            file_like=cStringIO.StringIO(self.image)

            return mark_safe(u'<img width="70" height="70" src="data:image/png;base64,%s" />') % file_like
        else:
            return '(No image)'
    image_thumb.short_description = 'Thumb'
    image_thumb.allow_tags = True

    class Meta:
        managed = False
        db_table = 'categories'

为避免数据库不必要的结构更改,我在 models.py 中将图像列类型更改为 models.ImageField。在数据库中,它是一个二进制字段。这样做并通过覆盖保存方法,我尝试解决问题。

1)但是当我尝试保存上传的文件时,我收到以下消息:

DjangoUnicodeDecodeError 在 /admin/app/categories/34/ “utf8”编解码器无法解码位置 0 中的字节 0x89:无效的起始字节。你传入了 '\x89PNG\r\n\x1a\n\x....

2) 我无法检索正确的格式来显示图像 file_like 变量

我使用 python 2.7 和 django 1.7

非常感谢任何帮助

【问题讨论】:

    标签: python django


    【解决方案1】:

    要使用 BinaryField,在模型中执行类似...

    image_file = models.BinaryField(blank=True)
    

    然后从表单中读取 POST...

    image_file = request.FILES['image_file'].file.read()
    

    就这么简单。

    【讨论】:

      【解决方案2】:

      尝试使用 Django 的内置 BinaryField 而不是 ImageField

      【讨论】:

      • 你能告诉我如何在我的情况下使用 BinaryField 吗?
      猜你喜欢
      • 2018-01-30
      • 1970-01-01
      • 2021-10-29
      • 2018-06-17
      • 2021-04-28
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      相关资源
      最近更新 更多