Max image size on file upload

django, django-forms, image-processing

Solution

models.py

class Product(models.Model):
    image = models.ImageField(upload_to="/a/b/c/")

forms.py

class ProductForm(forms.ModelForm):
    # Add some custom validation to our image field
    def clean_image(self):
        image = self.cleaned_data.get('image', False)
        if image:
            if image._size > 4*1024*1024:
                raise ValidationError("Image file too large ( > 4mb )")
            return image
        else:
            raise ValidationError("Couldn't read uploaded image")

Problem

I have an ImageField in my form. How would I enforce a file size min/max, something like -- ``` image = forms.ImageField(max_size = 2MB) ``` or ``` image = forms.ImageField(min_size = 100k) ``` Thank you.

Original source

Related problems