WTforms: 错误 "字段不存在
你好,我有一个表单类,长得像这样:
class UserCreateForm(wtf.Form):
name=wtf.TextField('Name',validators=[validators.Required(),username_check])
email=wtf.TextField('Email')
userimage=wtf.FileField(u'Upload Image',validators=[checkfile])
自定义的验证函数“checkfile”是这样的:
def checkfile(form,field):
if field.data:
filename=field.data.lower()
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
if not ('.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS):
raise ValidationError('Wrong Filetype, you can upload only png,jpg,jpeg,gif files')
else:
raise ValidationError('field not Present') # I added this justfor some debugging.
不过我发现,即使我在模板中选择了一个文件并点击提交,它总是会出现“字段不存在”的错误。我对此有点困惑。field.data 不是检查文件名是否存在的正确方法吗?
1 个回答
7
终于解决了这个问题,我在验证器里把 field.data
替换成了 field.file
,然后用 field.file.filename
来访问它的属性。