Auto rename file after uploaded

By: summonagus ● at Aug. 5, 2017, 8:24 a.m. ● and modified at Aug. 5, 2017, 8:26 a.m.
Posted under: #Tricks, #Problem, #Django, #Solution ● Your ip address: 54.224.184.33 ● views: 30 times.

AD Space Available, Book Now!

Django Auto rename file after uploaded. This method to handle duplicated files in same times. This snippet below is how to do that;

import os, time, uuid
from django.db import models
from django.utils.deconstruct import deconstructible


class ImageUploader(models.Model):

    @deconstructible
    class PathAndRename(object):

        def __init__(self, sub_path):
            self.path = sub_path

        def __call__(self, instance, filename):
            # eg: filename = 'my uploaded file.jpg'
            ext = filename.split('.')[-1]  #eg: 'jpg'
            uid = uuid.uuid4().hex[:10]    #eg: '567ae32f97'

            # eg: 'my-uploaded-file'
            new_name = '-'.join(filename.replace('.%s' % ext, '').split())

            # eg: 'my-uploaded-file_64c942aa64.jpg'
            renamed_filename = '%(new_name)s_%(uid)s.%(ext)s' % {'new_name': new_name, 'uid': uid, 'ext': ext}

            # eg: 'images/2017/01/29/my-uploaded-file_64c942aa64.jpg'
            return os.path.join(self.path, renamed_filename)

    image_path = time.strftime('images/%Y/%m/%d')
    image = models.ImageField(upload_to=PathAndRename(self.image_path))

If you need a validator, you can check this complete snippet.

Author

summonagus

Python Developer, Linux Enthusiast, and Senior writer at python.web.id
Website: https://github.com/agusmakmun
blog comments powered by Disqus