Skip to content Skip to sidebar Skip to footer

Django Filefield Move File Following Upload

There are several questions around this topic but not one that I've found that suits what I'm trying to do. I want to be able to upload a file to a model and save that file in a ni

Solution 1:

I figured it out after a lot of searching and finding this old documentation ticket that has a good explanation.

classUploadModel(models.Model):
    image = models.ImageField(upload_to='uploads')

    defsave(self, *args, **kwargs):

        # Call standard savesuper(UploadModel, self).save(*args, **kwargs)

        if'uploads'in self.image.path:

            initial_path = self.image.path

            # New path in the form eg '/images/uploadmodel/1/image.jpg'
            new_name = '/'.join(['images', self._meta.model_name, str(self.id), 
                path.basename(initial_path)])
            new_path = os.path.join(settings.MEDIA_ROOT, 'images', 
            self._meta.model_name, self.pk, os.path.basename(initial_path))

            # Create dir if necessary and move fileifnot os.path.exists(os.path.dirname(new_path)):
                makedirs(os.path.dirname(new_path))

            os.rename(initial_path, new_path)

            # Update the image_file field
            self.image_file.name = new_name

            # Save changessuper(UploadModel, self).save(*args, **kwargs)

Now I read the docs for this it looks totally obvious :) but I do think the explanation could be made more descriptive. Hopefully this will save someone some time!

Post a Comment for "Django Filefield Move File Following Upload"