http://mongoengine.org/docs/v0.4/guide约mongoengine的FileField我/gridfs.html 文档做了以下内容:

在我的模型

files = ListField(FileField())

在我的测试代码

    # Create an entry 
    photo = FileField()
    f  = open('/home/foo/marmot.jpg', 'r')   
    photo.put(f, content_type='image/jpeg')
    entry.files = [photo,]

试图跟随该文档,但我得到一个错误:

Traceback (most recent call last):
  File "/home/bar/tests.py", line 76, in test_MongoDGACLogook_creation
    photo.put(f, content_type='image/jpeg')
AttributeError: 'FileField' object has no attribute 'put'

我失去了一些东西明显?

由于

有帮助吗?

解决方案 2

    f = mongoengine.fields.GridFSProxy()
    to_read = open('/home/.../marmot.jpg', 'r')   
    f.put(to_read, filename=os.path.basename(to_read.name))
    to_read.close()

其他提示

这是在所有不明显IMO,但如果看看Mongoengine代码你会看到put方法在GridFSProxy类,其经由一个描述符在FileField存取未定义(__get____set__方法)

看代码和在该文档中的例子中,它出现的唯一方式访问或使用FileField是通过描述符....所以,collection.file_field

考虑到这一切,我不认为这是可能有使用Mongoengine API文件中的字段列表,因为它现在已经存在。

如果您所上传的倍数文件,并试图将其保存到ListField(的FileField())

<input type='file' name='myfiles' multiple="">

files = []
for f in request.FILES.getlist('myfiles'):
    mf = mongoengine.fields.GridFSProxy()
    mf.put(f, filename=f.name)
    files.append(mf)
entry.files = files
entry.save()

我有完全相同的问题。如这个帖子,我最后建议的@KoppeKTop GitHub上延长使用EmbeddedDocument这样我的模型(Pet):

class OneImage(mongoengine.EmbeddedDocument):
    element = ImageField()

class Pet(mongoengine.Document):
    photos = EmbeddedDocumentListField(OneImage)
    # ...more fields... #

我然后可以使用添加新的图像

    i = OneImage()
    i.element.put(form.photo.data.stream)
    entry.photos.append(i)
    entry.save()

这未必是最好的选择,但我个人更喜欢它,因为我可以用模型照常工作,而无需工作与代理。而且我还可以保存在今后其他照片的元数据,如果我需要。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top