Search code examples
pythondjangoamazon-s3django-storage

How to move files into another directory django-storage s3


I'm working on a news blog where you can add as many files to news as you want. For files storing properties, I'm using amazon s3 and django-strorage. But after I've added news-update view, I got some problems with files management.

As you can see, here my files model

class FileStorage(models.Model):
    file        = models.FileField(upload_to=uploadFile)
    upload_path = models.TextField(blank=True, default='files/')

    def __str__(self):
        return f'Файл: {self.file.name.split("/")[-1]}'

The main problem is how to update FileField after moving the file into another directory?

Here is my files moving script.

bucket = S3Boto3Storage()
from_path = bucket._normalize_name(bucket._clean_name(self.instance.file.name))
to_path = bucket._normalize_name(bucket._clean_name(self.cleaned_data['upload_path']))
    
result = bucket.connection.meta.client.copy_object(
    Bucket=bucket.bucket_name,
    CopySource=bucket.bucket_name + "/" + from_path,
    Key=to_path)
bucket.delete(from_path)

All works good, but only with path. File in FileField store old path. How can I update it to?

Screen with problem enter image description here


Solution

  • If you want this, just change your file "name" parameter like this:

    file.name = "new file path"