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

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

    I use something along these lines (note, "pip install filemagic" is required for this...):

    import magic
    def validate_mime_type(value):
        supported_types=['application/pdf',]
        with magic.Magic(flags=magic.MAGIC_MIME_TYPE) as m:
            mime_type=m.id_buffer(value.file.read(1024))
            value.file.seek(0)
        if mime_type not in supported_types:
            raise ValidationError(u'Unsupported file type.')
    

    You could probably also incorporate the previous examples into this - for example also check the extension/uploaded type (which might be faster as a primary check than magic.) This still isn't foolproof - but it's better, since it relies more on data in the file, rather than browser provided headers.

    Note: This is a validator function that you'd want to add to the list of validators for the FileField model.

    0 讨论(0)
提交回复
热议问题