How to save NamedTemporaryFile to a FileField model in Django?

I created a NamedTemporaryFile, added some content to it, and now I want to save it to the FileField model.

The problem is that I get SuspiciousOperation because the tmp directory is not in the FileSystemStorage directory.

What is the right way to do this?

+4
source share
2 answers

You want django to check it because it ensures that the file is placed inside the MEDIA_ROOT directory, so it is available for download.

In any case, you want to put the files outside of 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

+4
source

I ended up doing the oposite path romke explains: I am creating a temporary file in MEDIA_ROOT.

Another solution might work with the file in / tmp and then move it to MEDIA_ROOT.

My initial confusion arises from how forms work with downloaded files: they are in the / tmp directory (or in memory), and then they are automatically moved to the upload_to directory. I was looking for a general way to do this in Django.

+1
source

All Articles