Django文件上传大小限制 [英] Django File upload size limit

查看:1228
本文介绍了Django文件上传大小限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的django应用程序中有一个表单,用户可以上传文件。

如何为上传的文件大小设置限制,以便如果用户上传的文件大于我的限制,则该表单将被赢取

解决方案

此代码可能有助于:

 #添加到您的设置文件
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

#添加到包含FileField的表单,并相应地更改字段名称。
从django.template.defaultfilters导入文件大小
从django.utils.translation导入ugettext_lazy作为_
从django.conf导入设置
def clean_content(self):
content = self.cleaned_data ['content']
content_type = content.content_type.split('/')[0]
如果settings_type在settings.CONTENT_TYPES:
if content._size> settings.MAX_UPLOAD_SIZE:
raise forms.ValidationError(_('请保持文件大小在%s。当前文件大小%s')%(filesizeformat(settings.MAX_UPLOAD_SIZE),filesizeformat(content._size)))
否则:
raise forms.ValidationError(_('File type is not supported'))
返回内容

取自: Django Snippets - 根据文件内容类型和大小验证


I have a form in my django app where users can upload files.
How can i set a limit to the uploaded file size so that if a user uploads a file larger than my limit the form won't be valid and it will throw an error?

解决方案

This code might help:

# 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

Taken from: Django Snippets - Validate by file content type and size

这篇关于Django文件上传大小限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆