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',
You can do it in two ways
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])
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With