【问题标题】:Django/Pillow - Image resize only if image is uploadedDjango/Pillow - 仅在上传图像时调整图像大小
【发布时间】:2022-01-23 00:47:05
【问题描述】:

我可以上传图片并调整其大小,但如果我提交没有图片的表单,我会收到此错误

The 'report_image' attribute has no file associated with it.

没有图片上传怎么办?

这是我的models.py

class Report(models.Model):

    options = (
        ('active', 'Active'),
        ('archived', 'Archived'),
    )

    category = models.ForeignKey(Category, on_delete=models.PROTECT)
    description = models.TextField()
    address = models.CharField(max_length=500)
    reporter_first_name = models.CharField(max_length=250)
    reporter_last_name = models.CharField(max_length=250)
    reporter_email = models.CharField(max_length=250)
    reporter_phone = models.CharField(max_length=250)
    report_image = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True)
    date = models.DateTimeField(default=timezone.now)
    state = models.CharField(max_length=10, choices=options, default='active')

    class Meta:
        ordering = ('-date',)

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        img = Image.open(self.report_image.path)

        if img.height > 1080 or img.width > 1920:
            new_height = 720
            new_width = int(new_height / img.height * img.width)
            img = img.resize((new_width, new_height))
            img.save(self.report_image.path)


    def __str__(self):
        return self.description

【问题讨论】:

    标签: django django-models django-rest-framework python-imaging-library


    【解决方案1】:

    我找到了解决方案。需要在实际调整大小之前添加此检查。

    if self.report_image:

    这样,如果没有上传图片,它将忽略调整大小并继续进行。

    这是新的相关部分:

        def save(self, *args, **kwargs):
            super().save(*args, **kwargs)
    
            if self.report_image: #check if image exists before resize
                img = Image.open(self.report_image.path)
    
                if img.height > 1080 or img.width > 1920:
                    new_height = 720
                    new_width = int(new_height / img.height * img.width)
                    img = img.resize((new_width, new_height))
                    img.save(self.report_image.path)
    

    【讨论】:

    • 请记住,Stack Overflow 不仅仅是为了解决眼前的问题,而是为了帮助未来的读者找到类似问题的解决方案,这需要了解底层代码。这对于我们社区的初学者和不熟悉语法的成员来说尤其重要。鉴于此,您能否edit 您的答案包括对您正在做什么的解释以及为什么您认为这是最好的方法?
    猜你喜欢
    • 2019-02-10
    • 2014-07-18
    • 2020-03-10
    • 1970-01-01
    • 2015-08-06
    • 2011-10-24
    • 1970-01-01
    • 2017-06-26
    相关资源
    最近更新 更多