i 'm trying tp upload a file in Django use ImageField. I want to hash this img before upload (using ImageHash), and save the image with the hashed file name. Below is my code, can you helo me fix this?
models.py
from utils import hash_image
...
class: Subject(models.Model):
photo = models.ImageField(upload_to=hash_image)
...
utils
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
Error:
line 34, in hash_image
instance.file.open()
AttributeError: 'Subject' object has no attribute 'file'
You basically need something like this. And to address your error: your file is
instance.photo
notinstance.file
.But I'm not sure it can work with imagehash, because UploadedFile is not a file-like object. In particular Image.Open requires that the object implements
seek()
and UploadedFile does not do this. I don't see a way to construct an Image object here that imagehash will be able to use, but maybe somebody else can.