【发布时间】:2012-08-25 07:13:01
【问题描述】:
我需要在调用 super() 方法之前保存上传的文件。它应该被保存,因为我使用一些外部工具将文件转换为所需的内部格式。以下代码在上传文件“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_...'
似乎,它试图在无限循环中将其两次以相同的名称保存在super().save() 中。此外,它还会创建所有这些文件。
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)
编辑:
这是我想绕过的不优雅的方式(它会双重调用save() 方法):
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)
【问题讨论】:
-
translation_file.save() 有什么作用?我看不出在这个例子中什么会导致递归。
-
translation_file被定义为 FileField。但是方法在django.db.models.fields.files.py中引用了FieldFile。save()定义为def save(self, name, content, save=True):