Django: Validate file type of uploaded file

前端 未结 5 1520
栀梦
栀梦 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 23:31

    From django 1.11, you can also use FileExtensionValidator.

    from django.core.validators import FileExtensionValidator
    class UploadedFile(models.Model):
        file = models.FileField(upload_to=settings.XML_ROOT, 
            validators=[FileExtensionValidator(allowed_extensions=['xml'])])
    

    Note this must be used on a FileField and won't work on a CharField (for example), since the validator validates on value.name.

    ref: https://docs.djangoproject.com/en/dev/ref/validators/#fileextensionvalidator

提交回复
热议问题