如何将本地文件分配给Django中的FileField?

时间:2010-08-17 10:48:37

标签: python django filefield

我试图将文件从我的磁盘分配到FileField,但是我有这个错误:

AttributeError:'str'对象没有属性'open'

我的python代码:

pdfImage = FileSaver()
pdfImage.myfile.save('new', open('mytest.pdf').read())

和我的models.py

class FileSaver(models.Model):

    myfile = models.FileField(upload_to="files/")

    class Meta:
        managed=False

提前感谢您的帮助

2 个答案:

答案 0 :(得分:37)

Django使用它自己的file type(具有强大的增强功能)。无论如何,Django的文件类型就像decorator一样,所以你可以简单地将它包装在现有的文件对象周围,以满足Django API的需要。

from django.core.files import File

local_file = open('mytest.pdf')
djangofile = File(local_file)
pdfImage.myfile.save('new', djangofile)
local_file.close()

您当然可以通过编写以下内容(少一行)来装饰文件:

pdfImage.myfile.save('new', File(local_file))

答案 1 :(得分:0)

如果不想打开文件,也可以将文件移动到media文件夹,直接设置myfile.name为MEDIA_ROOT的相对路径

import os
os.rename('mytest.pdf', '/media/files/mytest.pdf')
pdfImage = FileSaver()
pdfImage.myfile.name = '/files/mytest.pdf'
pdfImage.save()