验证django中的多个文件

时间:2013-10-10 09:25:38

标签: python django django-models django-views

我想允许上传某些特定文件类型。我为一个特定的文件编写了下面的代码,它有效。

def validate_file_extension(value):
    if not value.name.endswith('.zip'):
       raise ValidationError(u'Error message')

但是我想允许多个文件,所以我在settings_dev中设置了这些文件,并编写了下面的代码,但没有工作。

def validate_file_extension(value):
    for f in settings_dev.TASK_UPLOAD_FILE_TYPES:
        if not value.name.endswith(f):
           raise ValidationError(u'Error message')

Settings_dev

TASK_UPLOAD_FILE_TYPES=['.pdf','.zip','.docx']

型号:

up_stuff=models.FileField(upload_to="sellings",validators=[validate_file_extension])

我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

如果TASK_UPLOAD_FILE_TYPES中有多个(不同的)文件类型,for循环将始终引发异常。因为任何一种文件类型都不匹配。

您不需要使用for,因为str.endswith接受元组作为参数。

>>> 'data.docx'.endswith(('.pdf','.zip','.docx'))
True
>>> 'data.py'.endswith(('.pdf','.zip','.docx'))
False

def validate_file_extension(value):
    if not value.name.endswith(tuple(settings_dev.TASK_UPLOAD_FILE_TYPES)):
       raise ValidationError(u'Error message')