GabiMe
GabiMe

Reputation: 18473

Django: How to limit size of uploaded image when using a ModelForm?

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

Upvotes: 0

Views: 4126

Answers (3)

anzel
anzel

Reputation: 31

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.

Upvotes: 2

sbaechler
sbaechler

Reputation: 1429

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
}

Upvotes: 0

Tom
Tom

Reputation: 1172

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

Upvotes: 0

Related Questions