le-doude
le-doude

Reputation: 3367

Django InMemoryUploadFile content and name manipulation

Hi I am still new to Django and Python and I have problem understanding the API, so it is totally possible I am missing something obvious.

I receive a file "through" the FileField of a forms.Form (Django). And thus manage to get an instance of InMemoryUploadedFile. This form is not linked to a Model. Before putting the file in a model and save it (I am using S3BotoStorage), I would like to change the file name and encrypt the file content (really now it's just doing nothing special I am still testing this).

What I do not understand is how to access the file name and data content of the file and overwrite it? or create a modified instance of my InMemoryUploadedFile.

I had in mind of using something like this, but obviously it doesn't work.

def encrypt(inMemFile, key):
    assert isinstance(inMemFile, InMemoryUploadedFile)
    secret = m2secret.Secret()
    secret.encrypt(inMemFile.read(), key)
    inMemFile.file = File(secret.serialize(), uuid.uuid4().get_hex())
    return inMemFile

Upvotes: 0

Views: 660

Answers (1)

sk1p
sk1p

Reputation: 6735

You can assign a File instance to the model field. Something like this should work:

obj = form.save(commit=False)
# [...] your encryption stuff [...]
obj.some_file_field = ContentFile(secret.serialize(), uuid.uuid4().get_hex())
obj.save()
form.save_m2m()

See also the second example of the section Handling uploaded files with a model in the Django documentation. Be aware that larger files are not handled in-memory; they are TemporaryUploadedFile instances.

Upvotes: 1

Related Questions