如何根据选择字段上的用户输入生成表单字段?
class PracticeForm(FlaskForm):
number_of_fields = SelectField(u'How many input fields?', choices=[(2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6')])
'''
dynamically create input fields based on user input of "number_of_fields" here
fields = number_of_fields (ranging from 2-6) **** StringFields with same attributes
'''
submit = SubmitField('Submit')
在我的route.py中,我想将这些字段保存到列表中:
@app.route("/practice", methods=['GET', 'POST'])
def practice():
practiceform = PracticeForm()
user_list = practiceform.fields.data
if practiceform.validate_on_submit():
return redirect(url_for('success_page', list=user_list))
我应该如何格式化表单以及如何在jinja2中格式化html页面,以便它显示SelectField以及基于SelectField中的数字的输入字符串字段的数目?
答案 0 :(得分:1)
基本上,您需要依靠jQuery / javascript来完成此操作-但这是使您前进的粗略示例:
from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import FieldList, StringField, SelectField
app = Flask(__name__)
app.secret_key = 'TEST'
class PracticeForm(FlaskForm):
min_choices, max_choices = 2, 6
choices = [(x, str(x)) for x in range(min_choices, max_choices)]
number_of_fields = SelectField(u'How many input fields?', choices=choices, coerce=int)
data_field = FieldList(StringField('Data'), min_entries=min_choices, max_entries=max_choices)
@app.route('/', methods=['POST', 'GET'])
def example():
form = PracticeForm()
if form.validate_on_submit():
print(form.data_field.data)
print(form.number_of_fields.data)
else:
print(form.errors)
return render_template('example.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
神奇之处在于FieldList
-现在,验证器将为此StringField
接受多个条目(介于最小和最大之间),并且可以很好地进行验证。
您的诀窍是现在使用jQuery读取SelectField的值-默认情况下将显示两个(因为这是分钟数),因此只需查看代码即可,您只需要看一看即可如果SelectField
的值发生变化,请采取措施。
例如-如果SelectField更改为3-,则需要插入:
<li>
<label for="data_field-2">Data</label>
<input id="data_field-2" name="data_field-2" type="text" value="">
</li>
这是对jQuery的一个非常粗糙的要求,它只是擦除<ul>
并根据所选字段的数量对其进行重建。
<form method="post" action="#">
{{ form.hidden_tag() }}
{{ form.number_of_fields }}
{{ form.data_field }}
<input type="submit"/>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
function range(start, end) {
return Array(end - start).fill().map((_, idx) => start + idx)
}
$('#number_of_fields').on('change', function() {
$('#data_field').empty();
range(0, (this.value * 1)).forEach(function(element) {
const reference = element;
$('#data_field').append(
'<li>' +
'<label for="data_field-'+ reference + '">Data</label> ' +
'<input id="data_field-'+reference+'" name="data_field-'+reference+'" type="text" value="">' +
'</li>'
);
});
});
</script>