为什么我会收到'FileField'对象没有'put'属性的错误?
根据http://mongoengine.org/docs/v0.4/guide/gridfs.html上关于mongoengine的FileField的说明,我做了以下操作:
在我的模型中
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'
我是不是漏掉了什么明显的东西?
谢谢
4 个回答
0
如果你正在上传多个文件,并且想把它们保存到一个列表字段(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()
2
这件事看起来并不明显,但如果你看看Mongoengine的代码,就会发现put
这个方法是在GridFSProxy
这个类里定义的,而这个类是通过FileField
中的一个描述符来访问的(也就是__get__
和__set__
这两个方法)。
从代码和文档中的例子来看,访问或使用FileField
的唯一方法似乎就是通过这个描述符,也就是说,你需要用collection.file_field
来访问。
考虑到这些,我觉得现在的Mongoengine API里不可能有一个文件字段的列表。
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()
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。