[Django]-Django aws S3 define upload file path and file dynamically

4👍

You can override the storage get_available_name method.

Here’s an example. Modify to get the exact filename scheme you want.

class MediaStorage(S3Boto3Storage):
    location = 'media/yy'
    file_overwrite = False

    def get_available_name(self, name, max_length=None):
        custom_name = f'/employeeid/{name}_randomnumber.png'
        return super().get_available_name(custom_name, max_length)

Docs: Writing a custom storage system

0👍

If you want to modify the location where your file is uploaded in a view, you can set the location attribute on the the S3 Storage Object associated with your upload:

from .models import ModelWithFileField

def my_view(request):
  # Assume the request to be handled contains some data to be uploaded in the
  # files attribute
  upload = request.FILES["file"]
  file_instance = ModelWithFileField(file_field=file)
  file_instance.file_field.storage.location = "someprefix"
  file_instance.save()

This works, but may be a quick and dirty solution. I don’t know if Storage objects are intended to work like this.

Leave a comment