django限制视图中的文件大小和文件格式

时间:2015-03-25 19:27:19

标签: python django filesize file-format

在我看来,我得到的文件如下:

def add_view(request):
    if request.method == "POST":
        my_files = request.FILES.getlist("file")
        for file in my_files:
            Here if file is greater than 2 Mb raise error and send error message
            Also check if the file is of type jpg. If it is then return something 

我该怎么做?我想通过从设置中获取常量变量来实现。比如在设置中设置MEDIA_TYPE或MIME_FORMAT,在设置

中设置文件大小

1 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

CONTENT_TYPES = ['image']
MAX_UPLOAD_PHOTO_SIZE = "2621440"
content = request.FILES.getlist("file")
content_type = content.content_type.split('/')[0]
if content_type in CONTENT_TYPES:
    if content._size > MAX_UPLOAD_PHOTO_SIZE:
        #raise size error
    if not content.name.endswith('.jpg'):
       #raise jot jpg error
else:
    #raise content type error

<强>已更新

如果您需要form验证,请尝试以下操作:

class FileUploadForm(forms.Form):
    file = forms.FileField()

    def clean_file(self):
        CONTENT_TYPES = ['image']
        MAX_UPLOAD_PHOTO_SIZE = "2621440"
        content = self.cleaned_data['file']
        content_type = content.content_type.split('/')[0]
        if content_type in CONTENT_TYPES:
            if content._size > MAX_UPLOAD_PHOTO_SIZE:
                msg = 'Keep your file size under %s. actual size %s'\
                        % (filesizeformat(settings.MAX_UPLOAD_PHOTO_SIZE), filesizeformat(content._size))
                raise forms.ValidationError(msg)

            if not content.name.endswith('.jpg'):
                msg = 'Your file is not jpg'
                raise forms.ValidationError(msg)
        else:
            raise forms.ValidationError('File not supported')
        return content