[Django]-Django Form Imagefield validation for certain width and height

3๐Ÿ‘

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")
    
๐Ÿ‘คJibin Mathews

1๐Ÿ‘

We need an image processing library such as PI to detect image dimension, here is the proper solution:

# Custom validator to validate the maximum size of images
def maximum_size(width=None, height=None):
    from PIL import Image

    def validator(image):
        img = Image.open(image)
        fw, fh = img.size
        if fw > width or fh > height:
            raise ValidationError(
            "Height or Width is larger than what is allowed")
     return validator

then in the model:

class Photo(models.Model):
    image = models.ImageField('Image', upload_to=image_upload_path, validators=[maximum_size(128,128)])
๐Ÿ‘คmrblue

Leave a comment