Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save a NamedTemporaryFile into a model FileField in Django?

Tags:

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?

like image 731
Grégoire Cachet Avatar asked Dec 18 '08 19:12

Grégoire Cachet


2 Answers

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

like image 162
rombarcz Avatar answered Oct 16 '22 19:10

rombarcz


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.

like image 43
Grégoire Cachet Avatar answered Oct 16 '22 20:10

Grégoire Cachet