一尘不染

文件上传时的最大图片大小

django

我的表单中有一个ImageField。我将如何实施文件大小的最小值/最大值,例如-

image = forms.ImageField(max_size = 2MB) 

要么

image = forms.ImageField(min_size = 100k)

谢谢。


阅读 429

收藏
2020-04-03

共1个答案

一尘不染

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")
2020-04-03