“Upload” a file from django shell

[亡魂溺海] 提交于 2019-12-30 01:12:48

问题


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).

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.

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()

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.


回答1:


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()



回答2:


If using Python 3 one adjustment is needed - change 'r' to 'rb':

f = File(open(os.path.join(IMPORT_DIR, 'fotos', photo), 'rb'))


来源:https://stackoverflow.com/questions/1232434/upload-a-file-from-django-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!