问题
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