Pergunta

I need to save an uploaded file before super() method is called. It should be saved, because i use some external utils for converting a file to a needed internal format. The code below produce an error while uploading file '123':

OSError: [Errno 36] File name too long: '/var/www/prj/venv/converted/usermedia/-1/uploads/123_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_...'

It seems, that it tries to save it in super().save() twice with the same name in an infinite loop. Also, it creates all these files.

def save(self, **kwargs):
    uid = kwargs.pop('uid', -1)
    for field in self._meta.fields:
        if hasattr(field, 'upload_to'):
            field.upload_to = '%s/uploads' % uid

    if self.translation_file:
        self.translation_file.save(self.translation_file.name, self.translation_file)

    #self.mimetype = self.guess_mimetype()
    #self.handle_file(self.translation_file.path)

    super(Resource, self).save(**kwargs)

EDIT: Here is inelegant way i wanted to get around (it will double call save() method):

def save(self, *args, **kwargs):
    uid = kwargs.pop('uid', -1)
    for field in self._meta.fields:
        if hasattr(field, 'upload_to'):
            field.upload_to = '%s/uploads' % uid

    super(Resource, self).save(*args, **kwargs)

    if self.__orig_translation_file != self.translation_file:
        self.update_mimetype()
        super(Resource, self).save(*args, **kwargs)
Foi útil?

Solução

You got an infinite loop in your first example, thats right. Calling self.translation_file.save(self.translation_file.name, self.translation_file) will save the uploaded file to disk and call the Resources class save method again because the methods save paramter defaults to true (have a look here https://docs.djangoproject.com/en/dev/ref/files/file/#additional-methods-on-files-attached-to-objects) as well as your custom FileField does anyway.

Calling it like this (just add save=False) is more likely to work:

self.translation_file.save(self.translation_file.name, self.translation_file, save = False)

I hope this points into the right direction.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top