我的自动完成视图正确匹配用户,但是两个用户返回相同的结果,因此我无法选择其中一个进行自动完成。它还返回对象名称,而不仅仅是用户名。例如,它会将<User 'kinwolf'>, <User 'kintest'>
作为字符串返回,而不仅仅是kinwolf, kintest
。如何让我的视图以正确的json格式返回用户名,以便自动完成工作?
@main.route('/list-members',methods=['GET','POST'])
@login_required
@admin_required
def find_member():
form = Find_member()
if form.validate_on_submit():
username = form.member_name.data
return redirect(url_for('.member',username=username))
return render_template('members_list.html',form=form)
#This route is a callback for the JQueryautocomplete
@main.route('/autocomplete',methods=['GET'])
def autocomplete():
search = request.args.get('term')
members = User.query.filter(User.firstname.like('%'+search+'%')).all()
member_list=str(members) #need to do this because it returns a value that is not JSONable
# print (member_list[member])
return jsonify(json_list=member_list)
class Find_member(Form):
member_name = StringField('Type the member full name:', validators=[DataRequired()])
submit = SubmitField('Search')
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %}Project-Z{% endblock %}
{% block page_content %}
<div class="page-header">
<h1> Members list </h1>
<h2>Find a member</h2>
<br>
<div class="col-md-4">
{{ wtf.quick_form(form) }}
</div>
</div>
{% endblock %}
{% block scripts %}
{{ super() }}
<script type="text/javascript">
$(function() {
$( "#member_name" ).autocomplete({
source: '{{url_for("main.autocomplete")}}',
minLength: 2,
});
});
</script>
{% endblock %}
答案 0 :(得分:1)
经过大量研究后,我看到另一篇帖子使用了另一种方法来对列表进行jsonify。我尝试了它并且它有效,我现在正确地收到了Web表单中的列表,我可以选择我想要自动完成的用户。
该行是
from flask import Response, json
return Response(json.dumps(member_list,),mimetype='application/json')
而不是
return jsonify(json_list=member_list)
我读到了我们不能再通过jsonify传递列表的原因是出于安全原因,遗憾的是。