python - 使用 FileField 并在烧瓶中一起验证的问题
问题描述
我正在使用 wtforms 来创建表单和验证。它是这样的:
class Test(FlaskForm):
image = FileField('تصویر', validators=[
FileAllowed(['jpg', 'png'], 'only image.')
])
year = IntegerField('سال', validators=[DataRequired(), year_check(max=15)])
month = IntegerField('سال', validators=[DataRequired(), NumberRange(1,31)])
day = IntegerField('روز', validators=[DataRequired(), NumberRange(1,31)])
def validate(self):
# import pdb; pdb.set_trace()
if not FlaskForm.validate(self):
return False
if self.year.data and self.month.data and self.day.data:
try:
d = JalaliDate(int(self.year.data), int(self.month.data) , int(self.day.data))
except:
self.day.errors.append('تاریخ اشتباه می باشد')
return False
return True
验证函数在jalali 日期中给出日、月和年,如果它们不是 valiead,则会产生验证错误。
html表单就像:
<form method="POST" action="" enctype="multipart/form-data" role="Post">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
<div class="custom-file">
{{ form.image.label (class_="custom-file-label") }}
{{ form.image(class_="custom-file-input") }}
</div>
在视图中我得到这样的文件字段:
file = request.files['image']
并将它们保存在数据库中。提交表单时显示此错误:
Bad Request
The browser (or proxy) sent a request that this server could not understand.
当我删除 FileField 或验证功能时,它可以正常工作。
解决方案
问题是这部分代码:
file = request.files['image']
当任何文件选择上传时发生错误。然后我更改了代码:
if 'image' in request.files:
file = request.files['image']
我从这里罚款
推荐阅读
- angular - 为 TSLint 自定义规则检查 @Injectable 装饰器的 AST
- c++ - 确定函数返回类型的最简单方法
- sql - 如何使用 LIKE 将一个字段与另一个字段进行比较
- asp.net-core - 如何获得“Asp.net Core 1.1”选项
- visual-studio-2017 - Wix Minimal UI 不显示
- python - Python for 循环仅识别块的第一行
- visual-studio - 在应用程序启动时从外部文件更改实体框架 6 连接字符串
- selenium - 无法使用 Selenium 定位元素
- sql-server - 夏威夷的 Azure Maps 和 SQL AT TIME ZONE 时区不兼容
- javascript - NW.js 当你的主文件是 JS 文件时如何调试?