Image rename on Upload to S3

12 views
Skip to first unread message

Mukul Mantosh

unread,
Jan 1, 2018, 7:12:04 AM1/1/18
to Django users
How to rename an image with FileField type. Please tell me how to do it in views while uploading an image to S3. 

import os
from uuid import uuid4

def path_and_rename(path):
    def wrapper(instance, filename):
        ext = filename.split('.')[-1]
        # get filename
        if instance.pk:
            filename = '{}.{}'.format(instance.pk, ext)
        else:
            # set filename as random string
            filename = '{}.{}'.format(uuid4().hex, ext)
        # return the whole path to the file
        return os.path.join(path, filename)
    return wrapper
FileField(upload_to=path_and_rename('upload/here/'), ...)
The above code works well in models.py file but throws back error during migration process. Please help me how can i solve this issue in views.py file because once i place the above code in models.py it works very well but if there is any change in model and i do a migration then it throws back an error.

Reply all
Reply to author
Forward
0 new messages