views:

322

answers:

1

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  A: 

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()
hchinchilla
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.
hughdbrown
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.
hchinchilla