Django/Pillow - 仅在上传图片时调整图片大小

Django/Pillow - Image resize only if image is uploaded

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

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

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

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)