Django模型函数,如果未提供任何图像,则保存ImageField =执行

时间:2019-03-31 19:05:23

标签: python django save

我有一个Django模型功能可以正确保存图像。目前,似乎Django-SmartFields当时存在问题,请参见:https://github.com/lehins/django-smartfields/issues/17,并且sorl无法正常工作,不知道为什么。 所以我很快就写下来了:

models.py

class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(verbose_name="Title", max_length=40)
    content = models.TextField(verbose_name="Content", max_length=5000)
    tag = models.CharField(verbose_name="Tags/Meta - (sep. by comma)", max_length=50, blank=True)
    category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)
    postattachment = fields.FileField(
        verbose_name="Attachment",
        blank=True,
        null=True,
        upload_to=get_file_path_user_uploads,
        validators=[file_extension_postattachment, file_size_postattachment]
    )
    postcover = fields.ImageField(
        verbose_name="Cover",
        blank=True,
        null=True,
        upload_to=get_file_path_user_uploads,
        validators=[default_image_size, default_image_file_extension]
    )
    up_vote = models.IntegerField(verbose_name='Post Up-Vote(s)', default=0)
    down_vote = models.IntegerField(verbose_name='Post Down-Vote(s)', default=0)
    published_date = models.DateField(auto_now_add=True, null=True)

    def save(self, *args, **kwargs):
        imageTemproary = Image.open(self.postcover)
        outputIoStream = BytesIO()
        imageTemproaryResized = imageTemproary.resize((700, 525))
        imageTemproaryResized.save(outputIoStream, format='JPEG', quality=85)
        outputIoStream.seek(0)
        self.postcover = InMemoryUploadedFile(outputIoStream, 'ImageField',
                                                  "%s.jpeg" % self.postcover.name.split('.')[0], 'image/jpeg',
                                                  sys.getsizeof(outputIoStream), None)
        super(Post, self).save(*args, **kwargs)

但是如果我现在想清除表格中的“图片”,则会出现以下错误:

  

“ postcover”属性没有与之关联的文件。

完整跟踪:

 Internal Server Error: /post/1/edit/
 Traceback (most recent call last):
   File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
     response = get_response(request)
  File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
   File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
     response = wrapped_callback(request, *callback_args, **callback_kwargs)
   File "/app/app_Accounts/decorators.py", line 33, in _wrapped_view
     return view_func(request, *args, **kwargs)
   File "/usr/local/lib/python3.6/site-packages/ratelimit/decorators.py", line 30, in _wrapped
     return fn(*args, **kw)
   File "/app/app/views.py", line 473, in post_edit
     post.save()
   File "/app/app/models.py", line 173, in save
     imageTemproary = Image.open(self.postcover)
   File "/usr/local/lib/python3.6/site-packages/PIL/Image.py", line 2638, in open
     fp.seek(0)
   File "/usr/local/lib/python3.6/site-packages/django/core/files/utils.py", line 20, in <lambda>
     seek = property(lambda self: self.file.seek)
   File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/files.py", line 41, in _get_file
     self._require_file()
   File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/files.py", line 38, in _require_file
     raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
ValueError: The 'postcover' attribute has no file associated with it.

做某事。对此行为有快速的解决方法?

提前谢谢

1 个答案:

答案 0 :(得分:1)

为什么不能检查图像是否存在

import os //added
def save(self, *args, **kwargs):
     super(Post, self).save(*args, **kwargs)
     if self.postcover:
         if os.path.exists(self.postcover.path):     //this was added
            imageTemproary = Image.open(self.postcover)
            outputIoStream = BytesIO()
            imageTemproaryResized = imageTemproary.resize((700, 525))
            imageTemproaryResized.save(outputIoStream, format='JPEG', quality=85)
            outputIoStream.seek(0)
            self.postcover = InMemoryUploadedFile(outputIoStream, 'ImageField',
                                                  "%s.jpeg" % self.postcover.name.split('.')[0], 'image/jpeg',
                                                  sys.getsizeof(outputIoStream), None)
     super(Post, self).save(*args, **kwargs)