Although Burkhan Khalid gave the answer, but I think this is still part of the puzzle. This still does not solve the problem of saving to the database. Here is a complete solution that also uses the newer with clause to take advantage of the Python and Django context_manager (so file.close () is not necessary, this happens automatically):
import hashlib class Image(models.Model): #... def save(self, *args, **kwargs): with self.image_file.open('rb') as f: hash = hashlib.sha1() if f.multiple_chunks(): for chunk in f.chunks(): hash.update(chunk) else: hash.update(f.read()) self.sha1 = hash.hexdigest() self.filesize = self.image_file.size super(Image, self).save(*args, **kwargs)
Note that super () is called in the with clause. This is important, otherwise you will receive an error message: ValueError: I/O operation on closed file. Django tries to read a closed file, thinking that it is open when you already closed it. This is also the last command to save everything that we updated to the database (this was left in the previous best answer, where you most likely have to call save () again to really save this data)
source share