"Upload" a file from django shell
Asked Answered
C

2

17

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.

Celestinacelestine answered 5/8, 2009 at 10:41 Comment(0)
C
25

Finally I found the answer.

from django.core.files import File

f = File(open(os.path.join(IMPORT_DIR, 'fotos', photo), 'rb'))
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()
Celestinacelestine answered 5/8, 2009 at 11:7 Comment(2)
So you changed from making an ImportFile object to making a File object? And ImportFile was derived from file, not File? It sounds like you could have fixed this by deriving ImportFile from File, but then I'm not sure what ImportFile was adding to the equation. From the code presented, it didn't seem to have a lot of specialized behavior.Cariole
First, when I tried to work with a file object django raised some exceptions like "f has no attribute chunks" so I created this class and write all the attributes needed to work.Celestinacelestine
D
7

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

f = File(open(os.path.join(IMPORT_DIR, 'fotos', photo), 'rb'))
Demit answered 11/7, 2014 at 13:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.