gpt4 book ai didi

python - 获取请求后坚持WTForm QuerySelectField值

转载 作者:行者123 更新时间:2023-12-03 17:00:31 24 4
gpt4 key购买 nike

当选择给定的下拉选项时,我正在寻找一种保留WTFForm QuerySelectField值的干净方法。这个想法是根据从QuerySelectField下拉列表中选择的给定技术过滤项目列表。我采用的方法是使用下拉菜单中的on change事件(即/ projects?id = 5)将get请求发送到/ projects,其中包含具有技术ID的查询字符串。
我通过以下方式进行结构化:

项目形式

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');
});


总结一下,我正在寻找所选的下拉菜单值,该值在on change事件之后仍然存在。我也愿意采用一种完全不同的方法,而不是同时传递查询字符串值。

最佳答案

如果我理解正确,那么现在需要的只是在请求页面设置GET arg id时设置Technology select字段。这样的事情应该起作用:

@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设计原则的代码。

关于python - 获取请求后坚持WTForm QuerySelectField值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41051237/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com