0

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

1

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

The problem is that this method actually called AFTER the image was already uploaded..
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)
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.
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.
0

Modern browser support client side file size checking. The big advantage is that you can reject a file before it has been uploaded.

if (typeof FileReader !== "undefined") {
    var size = document.getElementById('myfile').files[0].size;
    // check file size
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.