Validate Multiple files in django

笑着哭i 提交于 2021-01-29 08:13:57

问题


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')

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

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

Models:

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

how can I go about this?


回答1:


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.

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')


来源:https://stackoverflow.com/questions/19291904/validate-multiple-files-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!