Django - S3 - Access File Metadata

I have a simple model like so to store and track user uploaded documents:

class Document(...):
    file = models.FileField(..., upload_to=upload_to)
    ...

I am using the django-storage package to upload these files directly to s3.

However, s3 is limited in what characters are allowed in file names. I want to preserve the original file name in the meta data of the uploaded file.

I can easily set the meta data in my upload_to method, by I am having difficulty understanding how I can access this meta data without a hacky workaround. I like this process because I can see the original file name in S3 itself.

def upload_to(instance, filename):
    """ custom method to control how files are stored in s3 """

    # set metadata on uploaded file:    
    instance.file.storage.object_parameters.update({
        "Metadata" : {
            "original_name" : filename
        }
    })

    ...

The current solution I have is to use boto3 to grab the meta data, but is there a cleaner workaround?

def _get_original_file_name(file_field):
    """ method to extract metadat from a file field """

    # set up client:
    s3 = boto3.client('s3')

    # get head object:
    head_object = s3.head_object(
        Bucket=settings.AWS_STORAGE_BUCKET_NAME,
        Key=file_field.name,
    )

    # extract meta data set in upload_to method:
    original_name = head_object['Metadata']['original_name']

    return original_name

One solution:

I've also tried to create a custom S3FileField class that extends the FileField class and includes the above method, however I run into the following error. I'd be able to use this custom file field on all my models that have files if I can get it to work.

AttributeError: 'FieldFile' object has no attribute '_get_original_file_name'
Back to Top