首页 > 解决方案 > 使用 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 或验证功能时,它可以正常工作。

标签: pythonvalidationflaskflask-wtforms

解决方案


问题是这部分代码:

file = request.files['image']

当任何文件选择上传时发生错误。然后我更改了代码:

if 'image' in request.files:
    file = request.files['image']

我从这里罚款


推荐阅读