我想知道是否有人可以帮助我。
我希望能够点击客户,并且地理位置取决于特定客户,这是一个从属下拉列表。此信息来自数据库,因此在以下代码中进行查询。
这是我针对客户和位置的表单功能
class CustomerPick(SubForm):
customer = QuerySelectField(u'Customer',
get_label=u'sCustomer',
query_factory=lambda :
(TCustomer.query.order_by(TCustomer.sCustomer)),
validators=[DataRequired(),])
location = QuerySelectField(u'Location',
get_label=u'sLocation',
query_factory=lambda :
(TLocation.query.order_by(TLocation.sLocation)),
validators=[DataRequired(),])
这是视图部分
@route('new/', methods=['GET', 'POST'])
def new(self):
form = CustomerPick()
if form.validate_on_submit():
这是该下拉菜单的图片,也仅供参考,如果您还有其他需要尝试的地方,请告诉我。提前致谢! Photo
答案 0 :(得分:0)
我不太明白您的问题,但是您希望能够单击用户并根据位置填充下拉列表?
这涉及到一些Ajax来回发送数据。 我将为您提供最小化的代码段(未经测试)。
// front-end - this handles user behavior in dropdown. When a user changes a value
// in a user drop down, it will send a request to your Flask view function.
$("#user_drop_down").change(function () {
let user_identifier = this.value;
$.ajax({
type: "GET",
url:/url_to_flask_view_function/,
data: {user_identifier: user_identifier},
success: function (resp) {
$('#your_designated_div_for_both_dropdowns_div').html(resp.data)
}
});
});
# back-end - this receives the request sent from front-end and process the Flask-WTF
# form options so that it can render different options in the dropdowns. In this view
# function, we will return jsonified template with newly processed form_object
# instead of rendering the option data. You can return the json with only the data
# but it involves more javascript parsing and may be difficult for you.
@app.route('/url_to_flask_view_function/')
def form_processing():
user_identifier = request.args.get('user_identifier)
# now we've gotten the user_identifier, you will need to query. Below query is totally made up.
query_to_where_location = Location.query.filter(Location.user_identifier= user_identifier).first()
# your query result will not be in a tuple format
# if your query result is like this "locA, locB, locC, locD", you need to process
# it so that you make [('locA', 'locA'), ('locB', 'locB').......]
form_object = MyForm()
form_object.location.choices = processed_list
return jsonify({"data":render_template('template_that_contains_your_drodpdowns.html',
form_obj=form_obj)})
<!-- HTML piece, you should've had this already but make sure to specify your fields in HTML following Jinja2 synthax.-->
<form>
{{form_object.user}}
{{form_object.dropdown}}
</form>
总而言之,这里的想法是您使用.change
捕获用户行为,然后根据更改将带有user_identifier的请求发送到服务器端。一旦到达服务器端,您将对数据库进行查询,并以不同的处理形式再次呈现相同的模板。
执行此操作的最佳方法是,一旦将user_identifier放入视图中,便进行查询并返回jsonified位置对象,然后在成功代码块中,更改该下拉输入元素的。
如果您还有其他问题,请告诉我。