您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

一种非常简单的方法是使用自定义验证器。

在你的应用程序中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('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])
其他 2022/1/1 18:21:51 有543人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶