2016-07-24 10 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의 임시 보관 장소에 업로드 된 후에 발생합니다. 따라서 두 번째 부분은 정답입니다.