好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

django – 仅接受服务器端FileField中的某种文件类型

如何限制FileField只能以优雅的方式接受某种类型的文件(视频,音频,PDF格式等),服务器端? 一种非常简单的方法是使用自定义验证器.

在你的应用的validators.py中:

def validate_file_extension(value):
    import os
    from django.core.exceptions import ValidationError
    ext = os.path.splitext(value.name)[1]  # [0] returns path+filename
    valid_extensions = ['.pdf', '.doc', '.docx', '.jpg', '.png', '.xlsx', '.xls']
    if not ext.lower() in valid_extensions:
        raise ValidationError(u'Unsupported file extension.')

然后在你的models.py中:

from .validators import validate_file_extension

…并在表单字段中使用验证器:

class Document(models.Model):
    file = models.FileField(upload_to="documents/%Y/%m/%d", validators=[validate_file_extension])

另见:How to limit file types on file uploads for ModelForms with FileFields?.

查看更多关于django – 仅接受服务器端FileField中的某种文件类型的详细内容...

  阅读:22次