2016-07-24 37 views
0

我想为我的django文件上传实现文件大小& content_type限制。理想情况下,我想在我上传之前进行验证。最初我使用这个复制的代码,但它不工作。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

答案在问题中。模型验证在文件上传到django中的临时保存位置之后发生,而表单验证发生在上载之前。所以,第二部分是正确答案。