我正在寻找一种干净的方法来在选择给定的下拉选项时保留WTFForm QuerySelectField值。我们的想法是根据从QuerySelectField下拉列表中选择的给定技术过滤项目列表。我采用的方法是使用下拉列表中的on change事件(即/ projects?id = 5)向包含具有技术ID的查询字符串的/ projects发送get请求。 我通过以下方式构建它:
项目表格 -
class ProjectForm(ProjectFormBase):
title = StringField('Title', [validators.Length(min=4, max=25), validators.DataRequired()])
technology = QuerySelectField('Technology', query_factory= connect.technology_choices,
get_pk=lambda a: a.id,
get_label=lambda a: a.name, allow_blank=True, blank_text=u'Select a technology...')
项目路线 -
@app.route('/projects', methods=['GET', 'POST'])
def projects():
list_of_projects = None
form = ProjectForm(request.form)
technology_id = request.args.get('id')
if technology_id:
list_of_projects = connect.project(technology_id)
if request.method == 'GET':
if list_of_projects:
connect.close_connection()
return render_template("projects.html",
list_of_projects = list_of_projects, form = form)
else:
return render_template("projects.html", form=form)
JS -
$('#technology').on('change', function () {
var technology = $("#technology").value;
window.location.href="/projects?id=" + technology_id;
window.history.pushState('obj', 'newtitle', '/projects');
});
总而言之,我正在寻找所选择的下拉菜单值,以便在更改事件后保留。我也对一种完全不同的方法持开放态度,而不是传递查询字符串值。
答案 0 :(得分:0)
如果我理解正确,现在您只需要在设置GET arg id
的情况下请求页面时设置技术选择字段。这样的事情应该有效:
@app.route('/projects', methods=['GET', 'POST'])
def projects():
form = ProjectForm(request.form)
if request.method == 'GET':
technology_id = request.args.get('id')
# Set selected option on select field.
form.technology.data = technology_id
try:
list_of_projects = connect.project(technology_id)
connect.close_connection()
except:
list_of_projects = []
return render_template("projects.html",
list_of_projects=list_of_projects, form=form)
我还建议删除一些代码以符合Python的EAFP设计原则。