Skip to main content

Image Validator

To add validation for image file extensions only, you can create a custom validator and use it in your model field. Here's an example:

from django.core.exceptions import ValidationError
from django.utils.deconstruct import deconstructible
from django.utils.translation import gettext_lazy as _
import os

@deconstructible
class ImageValidator:
"""
Validate that the file extension is an image extension.
"""
message = _('File must be an image.')
code = 'invalid_image'

VALID_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif']

def __call__(self, value):
ext = os.path.splitext(value.name)[1]
if ext.lower() not in self.VALID_EXTENSIONS:
raise ValidationError(self.message, code=self.code)

class MyModel(models.Model):
image = models.ImageField(upload_to='images/', validators=[ImageValidator()])

In this example, ImageValidator is a custom validator that checks if the file extension is one of the supported image extensions. It uses a list of valid extensions and the os.path.splitext method to get the file extension of the uploaded file.

The validators argument of the ImageField is a list of validators, in this case containing only the ImageValidator. When a form is submitted with a file, the validators are run against the file, and if any validator raises a ValidationError, the form is considered invalid and the error is shown to the user.