</>
Validating image dimensions in Django REST Framework
When uploading an image through Django REST Framework, sometimes you want to validate data such as image dimensions or file size on a serializer level.
You can do it using a following snippet.
from rest_framework.exceptions import ValidationErrorfrom django.core.files.images import get_image_dimensionsMEGABYTE_LIMIT = 1REQUIRED_WIDTH = 200REQUIRED_HEIGHT = 200def logo_validator(image):filesize = image.sizewidth, height = get_image_dimensions(image)if width != REQUIRED_WIDTH or height != REQUIRED_HEIGHT:raise ValidationError(f"You need to upload an image with {REQUIRED_WIDTH}x{REQUIRED_HEIGHT} dimensions")if filesize > MEGABYTE_LIMIT * 1024 * 1024:raise ValidationError(f"Max file size is {MEGABYTE_LIMIT}MB")class OrganisationDetailSerializer(serializers.ModelSerializer):class Meta:model = Organisationfields = ('id', 'name', 'slug', 'logo',)slug = serializers.ReadOnlyField()logo = ImageField(validators=[logo_validator])