I have form in my django app. User can do prior upload of files before submitting the form. In handler for uploaded files I use TemporaryUploadedFile. So - files are stored in /tmp directory. This handler send the response to the form - JSON object, which contains file path and file extension. This information collects in array.
After submitting the form this array is serialized. And here is the problem - when the form handler receive form data and array of file names and try to access this files - here is the error "no such file".
So, my question is - how I can solve this problem? Maybe I can set the life time of this files for a bigger time? Or maybe I should use UploadedFile instead of TemporaryUploadedFile.
TIA!
TemporaryUploadedFile
uses tempfile.NamedTemporaryFile
. The Python docs have this to say:
tempfile.NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None[, delete=True]]]]]])
This function operates exactly as TemporaryFile() does, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked). That name can be retrieved from the name attribute of the file object. Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later). If delete is true (the default), the file is deleted as soon as it is closed (emphasis mine).
The returned object is always a file-like object whose file attribute is the underlying true file object. This file-like object can be used in a with statement, just like a normal file.
So, the default behavior here is to delete the file as soon as it's closed, which it will be, automatically after the initial processing. So you have two choices. You can either subclass TemporaryUploadedFile
and override the __init__
method so that you can pass delete=False
to tempfile.NamedTemporaryFile
(but then you need to remember to manually delete the file when you're done to avoid build-up of old temporary files), or you can make sure to move your TemporaryUploadedFile
somewhere else before returning from processing the upload, and send the new location back instead.
It would not be appropriate to use UploadedFile
because it's a base class and not intended to be instantiated, itself.