3๐
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")
๐ค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
- [Django]-Django โ Is there any way to hide superusers from the user list?
- [Django]-Django Rest Framework Filtering an object in get_queryset method
- [Django]-Solution to installing GDAL/PROJ/GEOS in windows 10 for Django/Geodjango
- [Django]-Django key based session expiration
Source:stackexchange.com