Django FieldFile无法在第一次打开时写入

时间:2014-04-25 23:50:12

标签: python django

我正在尝试写一个模型实例的FieldFile:

class SourceFile(models.Model):
    file_name = models.CharField('File Name', max_length = 100, unique=True)
    import_time = models.DateTimeField('Import Time', auto_now_add = True)
    local_link = models.FileField(upload_to="ozio/uploaded_files/%Y")

使用以下命令创建文件时没有问题:

source_file = SourceFile.objects.create(file_name = source_file_name)
source_file.local_link.save(source_file.file_name, ContentFile('LINE1'))

但是,当我尝试添加新行时:

source_file.local_link.open('a')  # Open as append mode
source_file.local_link.write('LINE2')

它抱怨道:

Traceback (most recent call last):
 File "<console>", line 1, in <module>
io.UnsupportedOperation: write

关闭它并重新打开时,一切看起来都不错。感谢任何建议。

>>> source_file, created = SourceFile.objects.get_or_create(file_name = 'Manual.2014.Q2.csv')
>>> source_file.local_link
<FieldFile: ozio/uploaded_files/2014/Manual.2014.Q2.csv>
>>> source_file.local_link.open('a')
>>> source_file.local_link.write('LINE2')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
io.UnsupportedOperation: write
>>> source_file.local_link.close()
>>> source_file.local_link.open('a')
>>> source_file.local_link.write('LINE2')
5
>>> source_file.local_link.close()
>>> source_file, created = SourceFile.objects.get_or_create(file_name = 'Manual.2014.Q2.csv')
>>> source_file.local_link.open('a')
>>> source_file.local_link.close()
>>> source_file.local_link.open('a')
>>> source_file.local_link.write('LINE3')
5
>>> source_file.local_link.close()
>>> 

0 个答案:

没有答案