How to limit file types on file uploads for ModelForms with FileFields?

后端 未结 7 781
星月不相逢
星月不相逢 2020-12-02 23:31

My goal is to limit a FileField on a Django ModelForm to PDFs and Word Documents. The answers I have googled all deal with creating a separate file handler, but I am not sur

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 00:04

    Validating with the extension of a file name is not a consistent way. For example I can rename a picture.jpg into a picture.pdf and the validation won't raise an error.

    A better approach is to check the content_type of a file.

    Validation Method

    def validate_file_extension(value):
        if value.file.content_type != 'application/pdf':
            raise ValidationError(u'Error message')
    

    Usage

    actual_file = models.FileField(upload_to='uploaded_files', validators=[validate_file_extension])
    

提交回复
热议问题