[Django]-How can I rename an uploaded file on Django before sending it to amazon s3 bucket?

0👍

Django provides API for that – it is upload_to parameter of the FileField object

https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.upload_to

upload_to may also be a callable, such as a function. This will be called to obtain the upload path, including the filename. This callable must accept two arguments and return a Unix-style path (with forward slashes) to be passed along to the storage system. The two arguments are:

The correct way to solve the problem would be to write a custom method and pass it to upload_to.

from converter.storage_backends import CsvStorage
from django.db import models
from django.utils import timezone


def modify_filename(instance, filename):
    return f"some-prefix-{filename}"

class CSVUpload(models.Model):
    csv_file = models.FileField(storage=CsvStorage(), upload_to=modify_filename)

    def __str__(self):
        return self.csv_file

Don’t override the save method! If you do so, then not only rename would be called every single time you want to save object to the database (even when not changing the file field), but also if you ever had optional file field in your object it would cause errors on your server

-1👍

You would need to override the save function. I did it something like this:

class Documents(AuditFields):
document_file = models.FileField(max_length=10000)

def save(self, *args, **kwargs):
    self.document_file.name = 'some_prefix' + self.document_file.name
    super(PlantDocument, self).save(*args, **kwargs)

Leave a comment