我有一个收集一些信息的表格,和一个允许用户上传文件的表格。这些都起作用。现在,我正在尝试制作一个将它们合并并从两者继承的表单。
我的文件上传表单具有FileRequired()验证器。当我仅访问上传表单时,此方法就可以通过了。如果我有合并的表单,尝试继承上传表单,则验证失败。但是,如果我删除FileRequired()验证程序,或者从其继承的窗体中删除它,或者通过替换组合窗体上的该字段,则文件可以正常上传。只有验证失败,而不是文件上传。我可以通过其他方式进行验证(检查request.files.getlist('<file>')
的长度,并且实际上已经在进行检查以防止用户上传太多文件,因此我有一种解决方法,但是我想了解为什么会这样失败。
这是我的views.py:
def add_scan(request, exp_id):
"""Add a scan"""
user_id = str(current_user.get_id())
if len(request.files.getlist('scan_file')) > 3:
flash('You can upload up to three files.', 'warning')
return redirect(url_for('scan.add'))
for f in request.files.getlist('scan_file'):
ScanService(user_id, exp_id).add(f)
flash('You successfully added a new scan.', 'success')
return redirect(url_for('experiment.experiments'))
@blueprint.route('/add', methods=['GET', 'POST'])
def add():
"""Access the add scan route and form."""
form = ScanForm()
if form.validate_on_submit():
exp_id = str(session['curr_experiment'])
return add_scan(request, exp_id)
else:
flash_errors(form)
return render_template('scans/upload.html',scan_form=form)
@blueprint.route('/add_experiment_and_scans', methods=['GET', 'POST'])
def add_experiment_and_scans():
"""Acess the add experiment and scans route and form"""
form = ExperimentAndScanForm(request.form)
if form.validate_on_submit():
exp_id = add_experiment(form)
return add_scan(request, exp_id)
else:
flash_errors(form)
return render_template('scans/experiment_and_scans.html', experiment_and_scan_form=form)
以下是表格:
class ExperimentForm(FlaskForm):
"""Experiment form."""
date = DateField('Date')
scanner = SelectField('Scanner', choices=[('GE', 'GE'), ('Sie', 'Siemens'), ('Phi', 'Phillips')])
field_strength = SelectField('FieldStrength', choices=[('1.5T', '1.5T'), ('3T', '3T'), ('7T', '7T')])
def __init__(self, *args, **kwargs):
"""Create instance."""
super(ExperimentForm, self).__init__(*args, **kwargs)
class ScanForm(FlaskForm):
scan_file = FileField(validators=[FileAllowed(['nii', 'nii.gz', 'zip']), FileRequired()])
submit = SubmitField('Submit')
def __init__(self, *args, **kwargs):
"""Create instance."""
super(ScanForm, self).__init__(*args, **kwargs)
class ExperimentAndScanForm(ExperimentForm, ScanForm):
def __init__(self, *args, **kwargs):
"""Create instance."""
super(ExperimentAndScanForm, self).__init__(*args, **kwargs)
对ScanForm
的验证成功,但对FileRequired()
的{{1}}失败。从ExperimentAndScanForm
中删除FileRequired()
(通过从ScanForm中删除它或替换ExperimentAndScanForm
中的scan_file
属性)可以上传文件。使用ExperimentAndScanForm
在scan_file
中创建新的ExperimentAndScanForm
属性会导致验证失败。
我不确定是否有帮助,但这是呈现此表单的模板:
FileRequired()