I have in my model an ImageField, and I am using forms.ModelForm to edit the form. I didn't find a way to make the ModelForm limit the uploaded image file size
3 Answers
Although this post is 2 years old, I come across to have a similar situation where even I raise the error, the file is still uploaded. What I have done to solve this is to replace the request.FILES['file'] with None, something like this:
#The max size in bytes
MAX_SIZE = 1000
for filename, file in request.FILES.iteritems():
if request.FILES['file'].size > MAX_SIZE:
request.FILES.pop(filename, None)
# return your errors here
and this solves the issue, the file will not be uploaded. Hope this helps others who come across with similar problem.
Comments
Here is some info about it: http://docs.djangoproject.com/en/1.2/topics/http/file-uploads/
Something like this:
#The max size in bytes
MAX_SIZE = 1000
if request.FILES['file'].size > MAX_SIZE:
#Lauch error
4 Comments
GabiMe
The problem is that this method actually called AFTER the image was already uploaded..
Tom
mm, i don't think that it is posible to check the file size before it is uploaded. maybe there is a javascript solution, but i don't think so.(it can be a security risk)
shreesh katti
Yea this will come into play once the image is uploaded but there is still option whether to save it or not. If the size exceeds the limit you can choose not to save it.
shreesh katti
If you want to check the size before uploading better to use some javascript functions to check the size of the image and restrict the user before uploading.