【问题标题】:Django - Get I/O error on changing object attributeDjango - 更改对象属性时出现 I/O 错误
【发布时间】:2014-05-27 00:41:32
【问题描述】:

在我的 views.py 文件中,我试图将 1 添加到名为 visited_counter 的 BigIntegerField。

views.py:

def view_page(request,id_page):

   page = get_object_or_404(Page,title=id_page)
   page.visited_counter= page.visited_counter +1
   page.save()

   return render(request,'app/page.html',locals())

models.py:

class Page(models.Model):
   title = models.CharField(max_length=30)
   visited_counter= models.BigIntegerField()
   landscape= models.BooleanField()
   thumbnail = models.ImageField(storage=OverwriteStorage(),upload_to=thumbnail_path)
   backgroundpicture =models.ImageField(storage=OverwriteStorage(),upload_to=background_path)

   def save(self, *args, **kwargs):

       if self.backgroundpicture.width >= self.backgroundpicture.height:
           self.landscape=True

       else:
           self.landscape=False

       if self.backgroundpicture:
           from PIL import Image
           import glob, os
           from cStringIO import StringIO
           from django.core.files.uploadedfile import SimpleUploadedFile

           image = Image.open(self.backgroundpicture)   ####LINE ERROR####

           try:
               # thumbnail
               THUMBNAIL_SIZE = (160, 160)  # dimensions

               # Convert to RGB if necessary
               if image.mode not in ('L', 'RGB'): image = image.convert('RGB')

               # create a thumbnail + use antialiasing for a smoother thumbnail
               image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)

               # fetch image into memory
               temp_handle = StringIO()
               image.save(temp_handle, 'JPEG')
               temp_handle.seek(0)

               # save it
               file_name, file_ext = os.path.splitext(self.backgroundpicture.name.rpartition('/')[-1])
               suf = SimpleUploadedFile(file_name + file_ext, temp_handle.read(), content_type='JPEG')

               self.thumbnail.save(file_name + '.jpg', suf, save=False)
           except ImportError:
               pass
       super(Page, self).save(*args, **kwargs)

当我创建一个“页面对象”时,我没有问题......保存功能做得很好,但是当我想通过view_page 功能访问该对象时。我在该行收到I/O operation on closed file 错误:image = Image.open(self.backgroundpicture)

我没有找到与此案例相关的任何其他 Q/A,所以我被困住了......

【问题讨论】:

    标签: python django model io save


    【解决方案1】:

    诀窍是在你的保存方法中添加一个 if 条件,并检查是否有必要在保存函数中读取整个代码。

    为此,您添加一个名为 has_changed 的函数

    def has_changed(instance, field, manager='objects'):
        """Returns true if a field has changed in a model
    
        May be used in a model.save() method.
    
        """
        if not instance.pk:
            return True
        manager = getattr(instance.__class__, manager)
        old = getattr(manager.get(pk=instance.pk), field)
        return not getattr(instance, field) == old
    

    你在模型定义中这样使用它:

    if has_changed(self, 'backgroundpicture'):
    
           if self.backgroundpicture.width >= self.backgroundpicture.height:
               self.landscape=True
    ...
    

    【讨论】:

      猜你喜欢
      • 2020-12-08
      • 2015-09-15
      • 2020-08-21
      • 2013-01-30
      • 1970-01-01
      • 2017-06-03
      • 2014-04-05
      • 1970-01-01
      • 2016-06-02
      相关资源
      最近更新 更多