如何将NamedTemporaryFile保存到Django中的模型FileField中?

时间:2022-07-13 19:16:28

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

我创建了一个NamedTemporaryFile,在其中添加了一些内容,现在我想将它保存到模型FileField中。

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

问题是我得到一个SuspiciousOperation,因为tmp目录不在FileSystemStorage目录中。

What's the proper way to do this?

这样做的正确方法是什么?

2 个解决方案

#1


You want django to check it for you because it ensures file is put inside MEDIA_ROOT dir so it's accessible for download.

您希望django为您检查它,因为它确保文件放在MEDIA_ROOT目录中,以便可以下载。

In any case you want to put files outside MEDIA_ROOT (in this case '/tmp') you should do something like this:

在任何情况下,你想把文件放在MEDIA_ROOT之外(在这种情况下'/ tmp')你应该做这样的事情:

from django.core.files.storage import FileSystemStorage
fs = FileSystemStorage(location='/tmp')

class YourModel(models.Model):
    ...
    file_field = models.FileField(..., storage=fs)

see Django documentation

请参阅Django文档

#2


I ended up doing the oposite way romke explains: I'm creating the temporary file in the MEDIA_ROOT.

我最终做了romke解释的对话方式:我正在MEDIA_ROOT中创建临时文件。

Another solution could be working with the file in /tmp and then moving it to MEDIA_ROOT.

另一个解决方案是使用/ tmp中的文件,然后将其移动到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.

我最初的困惑来自表单处理上传文件的方式:它们位于/ tmp目录(或内存)中,然后自动移动到upload_to目录。我一直在寻找在Django中执行它的通用方法。

#1


You want django to check it for you because it ensures file is put inside MEDIA_ROOT dir so it's accessible for download.

您希望django为您检查它,因为它确保文件放在MEDIA_ROOT目录中,以便可以下载。

In any case you want to put files outside MEDIA_ROOT (in this case '/tmp') you should do something like this:

在任何情况下,你想把文件放在MEDIA_ROOT之外(在这种情况下'/ tmp')你应该做这样的事情:

from django.core.files.storage import FileSystemStorage
fs = FileSystemStorage(location='/tmp')

class YourModel(models.Model):
    ...
    file_field = models.FileField(..., storage=fs)

see Django documentation

请参阅Django文档

#2


I ended up doing the oposite way romke explains: I'm creating the temporary file in the MEDIA_ROOT.

我最终做了romke解释的对话方式:我正在MEDIA_ROOT中创建临时文件。

Another solution could be working with the file in /tmp and then moving it to MEDIA_ROOT.

另一个解决方案是使用/ tmp中的文件,然后将其移动到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.

我最初的困惑来自表单处理上传文件的方式:它们位于/ tmp目录(或内存)中,然后自动移动到upload_to目录。我一直在寻找在Django中执行它的通用方法。