仅在服务器端的FileField中接受某种文件类型 [英] Only accept a certain file type in FileField, server-side

查看:203
本文介绍了仅在服务器端的FileField中接受某种文件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何限制 FileField 只能以优雅的方式(服务器端)接受某种类型的文件(视频,音频,pdf等) p>

How can I restrict FileField to only accept a certain type of file (video, audio, pdf, etc.) in an elegant way, server-side?

推荐答案

一个很简单的方法是使用自定义验证器。

One very easy way is to use a custom validator.

您的应用程序的 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

...并为您的表单字段使用验证器:

... and use the validator for your form field:

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

另请参见:如何使用FileFields限制ModelForms的文件上传文件类型?

这篇关于仅在服务器端的FileField中接受某种文件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆