Django: Validate file type of uploaded file

前端 未结 5 1493
栀梦
栀梦 2020-11-30 22:50

I have an app that lets people upload files, represented as UploadedFiles. However, I want to make sure that users only upload xml files. I know I can do this u

5条回答
  •  有刺的猬
    2020-11-30 23:28

    For posterity: the solution is to use the read method and pass that to magic.from_buffer.

    class UploadedFileForm(ModelForm):
        def clean_file(self):
            file = self.cleaned_data.get("file", False)
            filetype = magic.from_buffer(file.read())
            if not "XML" in filetype:
                raise ValidationError("File is not XML.")
            return file
    
        class Meta:
            model = models.UploadedFile
            exclude = ('project',)
    

提交回复
热议问题