Django文件上传大小限制

我在Django应用中有一个表单,用户可以在其中上传文件。

如何设置上传文件大小的限制,以便如果用户上传的文件大于我的限制,则该表格将无效并且会引发错误?

回答:

此代码可能会帮助:

# Add to your settings file

CONTENT_TYPES = ['image', 'video']

# 2.5MB - 2621440

# 5MB - 5242880

# 10MB - 10485760

# 20MB - 20971520

# 50MB - 5242880

# 100MB 104857600

# 250MB - 214958080

# 500MB - 429916160

MAX_UPLOAD_SIZE = "5242880"

#Add to a form containing a FileField and change the field names accordingly.

from django.template.defaultfilters import filesizeformat

from django.utils.translation import ugettext_lazy as _

from django.conf import settings

def clean_content(self):

content = self.cleaned_data['content']

content_type = content.content_type.split('/')[0]

if content_type in settings.CONTENT_TYPES:

if content._size > settings.MAX_UPLOAD_SIZE:

raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(settings.MAX_UPLOAD_SIZE), filesizeformat(content._size)))

else:

raise forms.ValidationError(_('File type is not supported'))

return content

以上是 Django文件上传大小限制 的全部内容, 来源链接: utcz.com/qa/434713.html

回到顶部