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

236
Views
Django/Pillow - Image resize only if image is uploaded

I'm able to upload an image and resize it, but if I submit the form without images I get this error

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

What should I do if no image is uploaded?

This is my 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

I found the solution. Needed to add this check before the actual resize.

if self.report_image:

This way, if no image has been uploaded it will just ignore the resize and proceed without it.

This is the new relevant part:

    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!