Puedo cargar una imagen y cambiar su tamaño, pero si envío el formulario sin imágenes, aparece este error
The 'report_image' attribute has no file associated with it.
¿Qué debo hacer si no se carga ninguna imagen?
Estos son mis 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.descriptionEncontré la solución. Necesario agregar esta verificación antes del cambio de tamaño real.
if self.report_image:
De esta manera, si no se ha cargado ninguna imagen, simplemente ignorará el cambio de tamaño y continuará sin él.
Esta es la nueva parte relevante:
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)