I created a NamedTemporaryFile, added some content in it and now I want to save it into a model FileField.
The problem is that I get a SuspiciousOperation because the tmp directory is not within the FileSystemStorage directory.
What's the proper way to do this?
You want django to check it for you because it ensures file is put inside MEDIA_ROOT dir so it's accessible for download.
In any case you want to put files outside MEDIA_ROOT (in this case '/tmp') you should do something like this:
from django.core.files.storage import FileSystemStorage
fs = FileSystemStorage(location='/tmp')
class YourModel(models.Model):
...
file_field = models.FileField(..., storage=fs)
see Django documentation
I ended up doing the oposite way romke explains: I'm creating the temporary file in the MEDIA_ROOT.
Another solution could be working with the file in /tmp and then moving it to MEDIA_ROOT.
My initial confusion comes from the way forms are working with uploaded files: they are located in the /tmp directory (or in memory) and then moved automatically to the upload_to directory. I was looking for a generic way of doing it in Django.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With