Skip to content

Instantly share code, notes, and snippets.

@Alir3z4
Created August 9, 2016 06:19
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save Alir3z4/725297248a59cae05a50b15dd79fb4d0 to your computer and use it in GitHub Desktop.
Save Alir3z4/725297248a59cae05a50b15dd79fb4d0 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)
@harunurkst
Copy link

harunurkst commented Jul 27, 2020

How I will use this upload_to() with my model?

@ellie
Copy link

ellie commented Aug 9, 2020

@harunurkst

Something like this:

    file = models.FileField(upload_to=upload_to)

Also, on line 16, you probably want

return "{0}{1}".format(hash_file(instance.file), filename_ext)

without the .

Can confirm this still works on Django 3, with Blake2b, and django-storages :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment