Django文件字段如何用流io填充

时间:2019-03-20 15:39:31

标签: django django-filer

我试图将当前不在磁盘上但存在于内存中的文件附加到模型中。 该模型使用django-filer,如果我通过常规文件,则该文件可以正常工作,如果使用io流,它将失败。

sequence_length

这是错误堆栈:

def test_save_bytesio():
from PIL import Image
import io

from django.core.files.uploadedfile import InMemoryUploadedFile
from django.core.files.uploadedfile import SimpleUploadedFile

img = Image.new("RGB",(4,4))
thumb_io = io.BytesIO()
img.save(thumb_io, format='JPEG')

# thumb_file = InMemoryUploadedFile(thumb_io, None, '{}_da_ordine.jpg'.format(1), 'image/jpeg',
#    thumb_io,None)
thumb_file = DjangoFile(thumb_io.getvalue(), name='gigi')
#thumb_file = DjangoFile(thumb_io, name='gigi')

mymodel = MyModelTosave.objects.create(
                 name='gigi',
                 file=thumb_file
               )

问题似乎出在这一行:

    return field.pre_save(obj, add=True)
../../.local/share/virtualenvs/--M2Y9QA9/lib/python3.7/site-packages/django/db/models/fields/files.py:288: in pre_save
    file.save(file.name, file.file, save=False)
../../.local/share/virtualenvs/--M2Y9QA9/lib/python3.7/site-packages/filer/fields/multistorage_file.py:121: in save
    content.seek(0)  # Ensure we upload the whole file
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <File: gigi>

>   seek = property(lambda self: self.file.seek)
E   AttributeError: 'bytes' object has no attribute 'seek'

../../.local/share/virtualenvs/--M2Y9QA9/lib/python3.7/site-packages/django/core/files/utils.py:20: AttributeError

将thumb_file传递到文件字段的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

尝试首先创建模型的实例,然后在save()上分别调用FileField,将BytesIO实例包装在Django的File中,例如:

from django.core.files import File

mymodel = MyModelTosave()
mymodel.file.save('gigi', File(thumb_io), True)

请注意,第三个参数True确保在文件保存完成后保存模型实例本身。

答案 1 :(得分:0)

在创建Djangofile之前添加此功能即可达到目的:

// K inferred as the full union "a" | "b" 
const fooAB = foo(Math.random() < 0.5 ? "a" : "b"); 
// fooAB is of type (typeof trans)["a" | "b"], the wide type from before
// better check it ourselves:
if ("valueA" in fooAB) {
    // fooAB is now known to be {valueA: string}
    console.log(fooAB.valueA) // okay
} else {
    // fooAB is now known to be {valueB: string}
    console.log(fooAB.valueB) // okay
}