Skip to content

Instantly share code, notes, and snippets.

@o3o3o
Forked from Alir3z4/utils.py
Created August 8, 2019 02:26
Show Gist options
  • Select an option

  • Save o3o3o/17b7d00004db8fb707ee2b89f64a2b21 to your computer and use it in GitHub Desktop.

Select an option

Save o3o3o/17b7d00004db8fb707ee2b89f64a2b21 to your computer and use it in GitHub Desktop.
Create a hash of a file on upload time and save it for Django FileField/ImageField
def hash_file(file, block_size=65536):
hasher = hashlib.md5()
for buf in iter(partial(file.read, block_size), b''):
hasher.update(buf)
return hasher.hexdigest()
def upload_to(instance, filename):
"""
:type instance: dolphin.models.File
"""
instance.file.open()
filename_base, filename_ext = os.path.splitext(filename)
return "{0}.{1}".format(hash_file(instance.file), filename_ext)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment