我想要一个搜索表单来查询数据库并在其下面显示搜索结果。刷新页面时,我不希望出现任何确认警告。我也想知道是否可以使用单个视图函数来完成,因为我所见过的所有教程都使用了不止一个。像this one和this one。
这是可行的,但是在单击浏览器上的刷新按钮时会显示警告,要求您确认:
main.py
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
form = SearchForm()
query = form.data['search']
if query != '':
results = Foo.query.filter(Foo.name.like('%'+query+'%')).all()
return render_template('index.html', form=form, query=query, results=results)
return render_template('index.html', form=form)
forms.py
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired
class SearchForm(FlaskForm):
search = StringField('search', validators=[DataRequired()])
templates / index.html
{% block page_content %}
<div class="page-header">
<form style="display: inline;" action="{{ url_for('index') }}" method="post" name="search">
{{ form.search(size=20) }}
<input type="submit" value="Search">
</form>
{% if results %}
<h1>Search results for "{{ query }}":</h1>
{{ results }}
{% endif %}
</div>
{% endblock page_content %}
这就是我想要的,但是它给出了page not redirecting properly error
:
@app.route('/', methods=['GET', 'POST'])
def index():
form = SearchForm(request.form)
if form.validate:
session['query'] = form.data['search']
return redirect(url_for('index'))
if 'query' in session:
results = Foo.query.filter(Foo.name.like('%'+session.get('query')+'%')).all()
return render_template('index.html', form=form, query=session.get('query'), results=results)
else:
return render_template('index.html', form=form)
答案 0 :(得分:3)
您可以使用一个功能来呈现搜索页面,然后在public function init()
{
parent::init();
\Yii::configure($this,
[
'as globalAccess' => [
'class' => BeforeActionValidator::class,
]
]);
}
之后查询数据库并返回结果。对于搜索结果,请添加if statetment,以将其显示在与搜索表单相同的模板上。
form.validate_on_submit()
search.html
@app.route('/search', methods=['GET', 'POST'])
def search():
form = SearchForm()
if form.validate_on_submit():
search_term = form.query.data
results = Foo.query.all()
return render_template('search.html', form=form, results=results)
return render_template('search.html', form=form)