验证Django中的多个文件 [英] Validate Multiple files in django
问题描述
我想允许某些特定文件类型上载.我为一个特定的文件编写了以下代码,它可以正常工作.
I want to allow some certain file types to be uploaded. I wrote the below code for one certain file, it worked.
def validate_file_extension(value):
if not value.name.endswith('.zip'):
raise ValidationError(u'Error message')
但是我想允许多个文件,因此我在settings_dev中设置了这些文件,并编写了以下代码,但不起作用.
but I want to allow more than one files, so I set those files in settings_dev, and wrote the below code, but not working.
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
Settings_dev
TASK_UPLOAD_FILE_TYPES=['.pdf','.zip','.docx']
型号:
up_stuff=models.FileField(upload_to="sellings",validators=[validate_file_extension])
我该怎么办?
推荐答案
如果 TASK_UPLOAD_FILE_TYPES
中有多种(不同的)文件类型,则 for
循环将始终提高例外.因为任何一种文件类型都不匹配.
If there are multiple (different) file types in TASK_UPLOAD_FILE_TYPES
, the for
loop will always raise the exception. Because any one of the file types does not match.
您不需要使用
,因为 str.endswith
接受一个元组作为参数.
You don't need to use for
because str.endswith
accepts a tuple as argument.
>>> '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')
这篇关于验证Django中的多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!