Django文件大小&表单级别与模型的content_type限制?

时间:2016-07-24 17:24:21

标签: python django validation

我正在尝试实现文件大小&我的django文件上传的content_type限制。理想情况下,我想在上传前验证。最初我使用这个转载的代码,但它无法正常工作。

class ContentTypeRestrictedFileField(FileField):
"""
Same as FileField, but you can specify:
    * content_types - list containing allowed content_types. Example: ['application/pdf', 'image/jpeg']
    * max_upload_size - a number indicating the maximum file size allowed for upload.
        2.5MB - 2621440
        5MB - 5242880
        10MB - 10485760
        20MB - 20971520
        50MB - 5242880
        100MB 104857600
        250MB - 214958080
        500MB - 429916160
"""
def __init__(self, *args, **kwargs):
    self.content_types = kwargs.pop("content_types", None)
    self.max_upload_size = kwargs.pop("max_upload_size", None)
    super(ContentTypeRestrictedFileField, self).__init__(*args, **kwargs)

def clean(self, *args, **kwargs):        
    data = super(ContentTypeRestrictedFileField, self).clean(*args, **kwargs)

    file = data.file
    try:
        content_type = file.content_type
        if content_type in self.content_types:
            if file._size > self.max_upload_size:
                raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(self.max_upload_size), filesizeformat(file._size)))
        else:
            raise forms.ValidationError(_('Filetype not supported.'))
    except AttributeError:
        pass        

    return data

到目前为止它根本不起作用。就像我只是使用常规的FileField。 但是,如果我在视图中这样做,我可以使它在表单级别工作,即:

if form.is_valid():
        file_name = request.FILES['pdf_file'].name

        size = request.FILES['pdf_file'].size
        content = request.FILES['pdf_file'].content_type
        ### Validate Size & ConTent here

        new_pdf = PdfFiles(pdf_file = request.FILES['pdf_file'])
        new_pdf.save()

最优选的方法是什么?

1 个答案:

答案 0 :(得分:1)

问题的答案就在于此。在将文件上载到django中的临时存放位置之后进行模型验证,同时在上载之前进行表单验证。所以,第二部分是正确答案。

相关问题