【问题标题】:AttributeError: 'Subject' object has no attribute 'file' when upload file in DjangoAttributeError:在 Django 中上传文件时,“主题”对象没有属性“文件”
【发布时间】:2020-07-15 12:27:54
【问题描述】:

我正在尝试在 Django 中使用 ImageField 上传文件。我想在上传之前对这个 img 进行散列(使用 ImageHash),并使用散列文件名保存图像。下面是我的代码,你能帮我解决这个问题吗?

models.py

 from utils import hash_image
 ...
 class: Subject(models.Model):
     photo = models.ImageField(upload_to=hash_image)
 ...

实用程序

    def hash_image(instance, filename):
        instance.file.open()
        ext = os.path.splitext(filename)[1]
        image_hash = ''
        image_hash = str(imagehash.average_hash(instance.file)) + '.' + ext
        return image_hash

错误:

line 34, in hash_image
        instance.file.open()
    AttributeError: 'Subject' object has no attribute 'file'

【问题讨论】:

  • Instance 是您的模型实例,而不是照片字段。
  • @Melvyn 谢谢你的信息,我该怎么办?

标签: python django imagehash


【解决方案1】:

你基本上需要like this。并解决您的错误:您的文件是instance.photo 而不是instance.file

但我不确定它是否可以与 imagehash 一起使用,因为 UploadedFile 不是类似文件的对象。特别是 Image.Open 要求对象实现 seek() 而 UploadedFile 不这样做。我没有看到一种方法可以在这里构造一个 imagehash 可以使用的 Image 对象,但也许其他人可以。

【讨论】:

  • 根据您的回答,我已将其修复如下:img = Image.open(instance.photo) image_hash = str(imagehash.average_hash(img)) 幸运的是,它起作用了
  • 哇,那我猜它不使用seek() 来处理这个工作负载。 :D
猜你喜欢
  • 2016-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-15
  • 1970-01-01
相关资源
最近更新 更多