Max image size on file upload

后端 未结 3 1157
南方客
南方客 2020-12-07 11:03

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

3条回答
  •  星月不相逢
    2020-12-07 11:40

    Here is another option that I didn't see across the variations of this question on stackoverflow: use a custom validator in your models. If you use this technique and a ModelForm in forms.py, then this should be all you need.

    models.py

    from django.core.exceptions import ValidationError
    
    class Product(models.Model):
        def validate_image(fieldfile_obj):
            filesize = fieldfile_obj.file.size
            megabyte_limit = 5.0
            if filesize > megabyte_limit*1024*1024:
                raise ValidationError("Max file size is %sMB" % str(megabyte_limit))
    
        image = models.ImageField(upload_to="/a/b/c/", validators=[validate_image])
    

提交回复
热议问题