Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Form Imagefield validation for certain width and height

I am trying to validate the image dimension in form level and display a message to user if submitted photo does not meet requirement which is image dimension 1080x1920. I dont want to store the width and height size in database. I tried with the Imagefield width and height attribute. But it is not working.

class Adv(models.Model):

    image = models.ImageField(upload_to=r'photos/%Y/%m/',
        width_field = ?,
        height_field = ?,
        help_text='Image size: Width=1080 pixel. Height=1920 pixel',
like image 488
Jhon Doe Avatar asked Dec 01 '25 02:12

Jhon Doe


1 Answers

You can do it in two ways

  1. Validation in model

    from django.core.exceptions import ValidationError

    def validate_image(image):
        max_height = 1920
        max_width = 1080
        height = image.file.height 
        width = image.file.width
        if width > max_width or height > max_height:
            raise ValidationError("Height or Width is larger than what is allowed")
    
    class Photo(models.Model):
        image = models.ImageField('Image', upload_to=image_upload_path, validators=[validate_image])
    
  2. Cleaning in forms

            def clean_image(self):
                image = self.cleaned_data.get('image', False)
                if image:
                    if image._height > 1920 or image._width > 1080:
                        raise ValidationError("Height or Width is larger than what is allowed")
                    return image
                else:
                    raise ValidationError("No image found")
    
like image 124
Jibin Mathews Avatar answered Dec 03 '25 04:12

Jibin Mathews



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!