簡體   English   中英

表單級別與模型級別的Django文件大小和content_type限制?

[英]Django file size & content_type restriction at form level vs model?

我正在嘗試為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()

最優選的方法是什么?

答案就在問題上。 在將文件上傳到django中的臨時存儲位置之后,進行模型驗證,而在上傳之前進行表單驗證。 因此,第二部分是正確的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM