How to validate file size in ImageField/FileFiled in Django

For this task we may create validate_image function and add it to validators attribute of ImageField.

# file models.py
from django.core.exceptions import ValidationError

def validate_image(image):
    file_size = image.file.size
    limit_kb = 150
    if file_size > limit_kb * 1024:
        raise ValidationError("Max size of file is %s KB" % limit)

    #limit_mb = 8
    #if file_size > limit_mb * 1024 * 1024:
    #    raise ValidationError("Max size of file is %s MB" % limit_mb)

class Photo(models.Model):
    image = models.ImageField('Image', upload_to=image_upload_path, validators=[validate_image])
comments powered by Disqus