Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

230
Views
Django/Pillow: cambia el tamaño de la imagen solo si se carga la imagen

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.description
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Encontré 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)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!