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

后端 未结 7 783
星月不相逢
星月不相逢 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:15

    Create a validation method like:

    def validate_file_extension(value):
        if not value.name.endswith('.pdf'):
            raise ValidationError(u'Error message')
    

    and include it on the FileField validators like this:

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

    Also, instead of manually setting which extensions your model allows, you should create a list on your setting.py and iterate over it.

    Edit

    To filter for multiple files:

    def validate_file_extension(value):
      import os
      ext = os.path.splitext(value.name)[1]
      valid_extensions = ['.pdf','.doc','.docx']
      if not ext in valid_extensions:
        raise ValidationError(u'File not supported!')
    

提交回复
热议问题