Codesnippet.dev
</>

Validating image dimensions in Django REST Framework

django drf rest test image processing

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 ValidationError
from django.core.files.images import get_image_dimensions
MEGABYTE_LIMIT = 1
REQUIRED_WIDTH = 200
REQUIRED_HEIGHT = 200
def logo_validator(image):
filesize = image.size
width, 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 = Organisation
fields = ('id', 'name', 'slug', 'logo',)
slug = serializers.ReadOnlyField()
logo = ImageField(validators=[logo_validator])