[上载"一个来自django shell的文件 [英] "Upload" a file from django shell
问题描述
我需要从一个excel文件和一个带有图像的文件夹中导入一些数据,Excel中的每一行描述每个条目,并在文件夹中列出文件名(与该条目有关的照片)。
I need to import some data from a excel file and a folder with images, every row in the excel describes every entry and have a list of filenames in the folder (photos related to the entry).
我已经完成了一个脚本,它创建数据库中的每个条目,并通过django shell保存它,但我不知道如何实例化一个InMemoryUploadedFile,以保存它与模型。
I've done a script which creates every entry in the database and saves it trough the django shell, but i have no idea how to instantiate a InMemoryUploadedFile for save it with the model.
在django 1.0中,我有这个小班让我做我需要的,但是在django 1.1中有变化,它不再起作用了。
In django 1.0 I had this small class which allowed me to do what i need, but with changes in django 1.1 it's not working any more.
class ImportFile(file):
def __init__(self, *args, **kwargs):
super(ImportFile, self).__init__(*args, **kwargs)
self._file = self
self.size = os.path.getsize(self.name)
def __len__(self):
return self.size
def chunks(self, chunk_size=None):
self._file.seek(0)
yield self.read()
我正在使用此类代码加载图像并使用模型实例保存。
I was using this class with this piece of code to load images and saving them with the model instance.
for photo in photos:
f = ImportFile(os.path.join(IMPORT_DIR, 'fotos', photo), 'r')
p = Photo(name=f.name, image=f, parent=supply.supply_ptr)
name = str(uuid1()) + os.path.splitext(f.name)[1]
p.image.save(name, f)
p.save()
问题是,如何从python中的文件创建InMemoryUploadedFile或TemporaryUploadedFile? ,或任何其他可以在这种情况下工作的东西。
The question is, how do I create a InMemoryUploadedFile or TemporaryUploadedFile from a file in python?, or any other thing that could work in this context.
推荐答案
最后我找到了答案。 b
Finally I found the answer.
from django.core.files import File
f = File(open(os.path.join(IMPORT_DIR, 'fotos', photo), 'r'))
p = Photo(name=f.name, image=f, parent=supply.supply_ptr)
name = str(uuid1()) + os.path.splitext(f.name)[1]
p.image.save(name, f)
p.save()
这篇关于[上载"一个来自django shell的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!