【发布时间】:2019-03-27 15:23:11
【问题描述】:
稍后更新...我终于解决了我的问题。我只是想知道是否有办法做到这一点更多 优雅?
我刚开始使用Python3、Flask 和Jquery 进行编程。
我的目标是让一个SelectField 根据另一个SelectField 的选项更改其值。就像,当我选择美国作为国家时,然后在 ajax 帮助下自动从数据库中加载州(比如纽约/华盛顿特区/...)。
现在我可以使用 ajax 调用获取数据,这意味着我可以在浏览器的调试模式下看到响应。我只是不知道如何用响应数据填充特定的SelectField。下面是相关代码sn-p。在此先感谢您的时间。
choose.html
<html>
<head>...</head>
<body>
...
<div class="row">
<form action="{{url_for('some_view_function')}}" method="post">
...
<div class="col-md-4 col-sm-4 col-xs-12">
{{ form.country(class="form-control select2_single") }}
</div>
<div class="col-md-4 col-sm-4 col-xs-12">
{{ form.state(class="form-control select2_single") }}
</div>
...
</form>
</div>
...
<script>
$(document).ready(function(){
$("#country").change(function(){
country_id=$("#country").val();
$.get("{{ url_for('get_states_by_country') }}",
{"country_id":country_id},
function(data, status){
if (status == 'success') {
// What should I do here with data?
}
});
});
});
</script>
</body>
</html>
view_function.py
@app.route('/obtain/states', methods={'GET', 'POST'})
def get_states_by_country():
country_id = request.args.get("country_id")
states = State.query.filter_by(
country_id=country_id
)
return jsonify(
{int(s.state_id): s.state_name
for s in states}
)
form.py
class LinkChooseForm(Form):
country = SelectField(label='Country')
state = SelectField(label='State')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.country.choices = [(c.id, c.name) for c in Country.query.all()]
self.state.choices = [] # I leave it empty when initiating
更新 1:
数据为json 格式。模拟数据如下。 key 是<option> 的value,value 是<option> 的text。
{
"bash", "desc_for_bash",
"csh", "desc_for_csh",
...
}
更新 2:
在@Deepak 的帮助下,我终于解决了这个问题。我在@Deepak 的回答(表单不接受选择选项)下提到的问题是错误的。事实上,form 确实接受了我的html 页面上的选择选项。我对其进行了调试,发现我想在我的操作函数中重置state.choices。您可能会注意到我在启动表单对象时将state.choices 留空。但是flask-wtf 将验证您在页面上的选择是否是state.choices 之一。这显然不是,因为我把它留空了。所以我必须用request.form.get('state') 重置它以满足flask-wtf 的验证。下面是提交功能。
@app.route('/test', methods={'GET', 'POST'})
def some_view_function():
form = LinkChooseForm(**request.view_args)
if request.method == 'POST':
# The most important part here.
form.state.choices = [(request.form.get('state'), "")]
if form.validate_on_submit():
action_entity = ActionEntity()
action_entity.do(form)
return redirect(url_for('.another_view_function'))
else:
# reset it as empty again
form.state.choices = []
return render_template(
'result.html',
form=form
)
【问题讨论】:
-
你为什么不能使用插件。你为什么要转储数据库
-
cssscript.com/demo/… 请参考这个。希望这有帮助
-
@Deepak 感谢您的宝贵时间。但我在这里提出的只是一个例子。其实我有两个有特定业务含义的
SelectFields,而不是country和state。 -
你能把你的 json 数据或者一个 mock json 贴出来让我写代码
-
@Deepak 我编辑了我的帖子,够了吗?谢谢。
标签: jquery ajax python-3.x flask-wtforms