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.
The upload module limits the size of a single attachment to be less than either post_max_size, or upload_max_filesize, whichever is smaller. The default PHP values are 2 MB for upload_max_filesize, and 8 MB for post_max_size.
JPEG/JFIF supports a maximum image size of 65,535×65,535 pixels, hence up to 4 gigapixels for an aspect ratio of 1:1.
By default, IIS web server allows for limited file size to be uploaded to the web server. For IIS 6 and IIS 7, the default maximum file upload size is 4 MB and 28.6 MB respectively.
Essentially this is a duplicate of Django File upload size limit
You have two options:
Use validation in Django to check the uploaded file's size. The problem with this approach is that the file must be uploaded completely before it is validated. This means that if someone uploads a 1TB file, you'll probably run out of hard drive space before the user gets a form error.
Configure the Web server to limit the allowed upload body size. e.g. if using Apache, set the LimitRequestBody
setting. This will mean if a user tries to upload too much, they'll get an error page configurable in Apache
As @pastylegs says in the comments, using a combination of both is probably the best approach. Say you want a maximum of 5MB, perhaps enforce a 20MB limit at the Web server level, and the 5MB limit at the Django level. The 20MB limit would provide some protection against malicious users, while the 5MB limit in Django provides good UX.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With