【问题标题】:I/O operation on closed file when saving a model保存模型时对关闭文件的 I/O 操作
【发布时间】:2016-02-23 19:56:10
【问题描述】:

大家好,我在代码的这一部分有我的问题。我从全局变量上传了多个文件。

file_car = None # Global variable

在我看来.py

    if request.method == 'POST':
         if file_car is None:
         print request.FILES
         file_car = [request.FILES.get('dzfile[%d]' % i)
         for i in range(0, len(request.FILES))]

我需要这样使用,因为我需要在很多其他视图中使用这些图像。但问题是当我想保存时

 for f in file_car:
            print f
            myfyle= File(f)
            #myfyle.open()
            aux = Attachment()
            aux.name= f
            aux.car = car
            aux.save() # here is the error. I tried opening the file but it said you cannot reopen the file

它让我对关闭的文件进行 I/O 操作。我对此感到抓狂。对不起我的英语不好

如果有帮助,这里是一个更具压缩性的代码

 from django.core.files import File
def createCarView(request):
        global file_car
        if request.method == 'POST': 
            if file_car is None:
                form = CarForm(request.POST, request.FILES) # other valus
                print request.FILES # Print all the file that I get
                file_car = [request.FILES.get('dzfile[%d]' % i)
                    for i in range(0, len(request.FILES))] # Have all the fileS!
                if form.is_valid():
                            # omitted all the other part of the form!    
                            car.save()  
                            for f in file_car:
                              print f
                              #myfyle.open()
                              aux = Attachment()
                              aux.name=myfyle
                              aux.car = car
                              aux.save() #Error in here
                              print aux.name
                              file_car=None # cleaning the global var     
                              return HttpResponseRedirect('/car/create') 

models.py

class Attachment(models.Model):
    car = models.ForeignKey('Car', on_delete=models.CASCADE)
    name = models.FileField(_('File'),
        upload_to=upload_to_get,
        )

【问题讨论】:

  • 哪一行出现 I/O 错误?
  • aux.save 给我报错
  • FileAttachment 类是什么?
  • 如果代码更具压缩性,则添加编辑

标签: python django file


【解决方案1】:

代码不清楚,但错误提示您应该打开文件,那么尝试这样的事情怎么样? :

 for f in file_car:
     with open(f,"a") as f:
         print f
         myfyle= File(f)
         aux = Attachment()
         aux.name=myfyle
         aux.car = car
         aux.save()

【讨论】:

  • 已经试过了 给我抛出这个强制 Unicode 的错误:需要字符串或缓冲区,找到 InMemoryUploadedFile
猜你喜欢
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 2021-05-12
  • 1970-01-01
  • 1970-01-01
  • 2013-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多