Skip to content

image type validators

utils/image-type-validators.py

from PIL import Image
from django.core.exceptions import ValidationError

def validate_image_type(image):
    """
    Validate the uploaded image.
    """
    try:
        # Open the image file
        img = Image.open(image)

        # Ensure it's in a supported format
        supported_formats = ('JPEG', 'PNG', 'GIF', 'WEBP')
        if img.format not in supported_formats:
            raise ValidationError("Unsupported image format. Supported formats: JPEG, PNG, GIF")

        # Additional validation checks can be added here if needed

    except IOError:
        # Unable to open image file
        raise ValidationError("Invalid image file")

Usage

models.py

from django.db import models
from utils.image_type_validators import validate_image_type

class YourModel(models.Model):
    image = models.ImageField(upload_to='gallery/')

    def clean(self):
        """
        Validate the uploaded image before saving.
        """
        if self.image:
            validate_image_type(self.image)

    def save(self, *args, **kwargs):
        """
        Override the save method to perform image validation before saving.
        """
        self.clean()
        super().save(*args, **kwargs)