Search code examples
djangofilenamesfilefield

Django - UploadFile - Change name


I need to rename the file with the name of the variable.

I Have this:

    def content_file_name_Left(instance, filename):
        return 'user_{0}/Left/{1}'.format(instance.ID, filename)

...

     user_ImageLeft = models.FileField(default='', upload_to=content_file_name_Left)

I want that its save in: user_x/Left/user_ImageLeft.[format]

I have 20 images and I don't want make 20 functions for write manually the name of the variable.

Thanks


Solution

  • Just tested this and the best way seems to be by using a deconstructible class (deconstructible is used to prevent migration errors):

    @deconstructible
    class PathAndUniqueFilename(object):
        def __init__(self, sub_path):
            self.path = sub_path
    
        def __call__(self, instance, filename):
            self.path = self.path.format(instance.user.id)
            return os.path.join(self.path, filename)
    

    and then call this in your model like so:

    user_ImageLeft = models.FileField(default='', upload_to=PathAndUniqueFilename('user_{0}/Left/'))
    

    What this does is take the parameters of PathAndUniqueFilename('user_{0}/Left/'), and uses format() in the deconstructible in order to add a custom folder name.