Skip to content

Instantly share code, notes, and snippets.

@yxkelan
Created November 2, 2012 06:15
Show Gist options
  • Save yxkelan/3999031 to your computer and use it in GitHub Desktop.
Save yxkelan/3999031 to your computer and use it in GitHub Desktop.
Limit the uploaded file size Django
#In form.py
#The original source for this : http://djangosnippets.org/snippets/1303/
from django import forms
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _
# 2.5MB - 2621440
# 5MB - 5242880
# 10MB - 10485760
# 20MB - 20971520
# 50MB - 5242880
# 100MB 104857600
# 250MB - 214958080
# 500MB - 429916160
MAX_UPLOAD_SIZE = "5242880"
class UploadFileForm(forms.ModelForm):
def clean(self):
self.check_file()
return self.cleaned_data
def check_file(self):
content = self.cleaned_data["event_file"]
content_type = content.content_type.split('/')[0]
if content._size > int(MAX_UPLOAD_SIZE):
raise forms.ValidationError(_("Please keep file size under %s. Current file size %s")%(filesizeformat(MAX_UPLOAD_SIZE), filesizeformat(content._size)))
return content
class Meta:
model = EventFile
@mooru
Copy link

mooru commented Oct 8, 2018

This bring out this error
'InMemoryUploadedFile' object has no attribute '_size'

@IgorMalyga
Copy link

This bring out this error
'InMemoryUploadedFile' object has no attribute '_size'

try content.size

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment