Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
868 views
Welcome To Ask or Share your Answers For Others

1 Answer

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...