我喜欢使用wtforms构建的搜索栏,但是由于某些原因,我不知道我无法获取在搜索栏中输入的数据或值。我几乎尝试了在线教程中的所有内容,但找不到解决方案。下面是我的代码示例。
对于我的搜索栏,我也尝试过 form.search.data 和 request.form ['search'] ,但无法正常工作。
#flask_app.py
from flask import Flask, render_template, url_for, flash, redirect, request
from forms import SearchForm
app = Flask(__name__)
app.config['SECRET_KEY'] = '791628bb0b13ce0c676dfde'
@app.route('/')
@app.route('/home')
def home():
return render_template('home.html')
@app.route('/search', methods= ['GET', 'POST'])
def search():
form = SearchForm()
if form.validate_on_submit():
if form.search.data == 'admin':
return redirect(url_for('home'))
return render_template('search.html', form= form)
if __name__ == "__main__":
app.run(debug=True)
#forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
class SearchForm(FlaskForm):
search = StringField('search', validators=[DataRequired()])
submit = SubmitField('Search')
#search.html
{% extends 'layout.html' %}
{% block content %}
<form action="" class="form-inline mt-4" method="POST">
<div class="form-group">
{{form.search(class= 'form-control', placeholder= 'Enter term to search')}}
{{form.submit(class= 'btn btn-outline-primary')}}
</div>
</form>
{%endblock%}
#home.html
{% extends 'layout.html' %}
{% block content %}
<h1>Welcome to homepage!</h1>
{%endblock%}
是否有任何错误?我希望 form.search.data 应该能够从搜索栏中获取数据。
答案 0 :(得分:1)
您没有以form.hidden_tag()
#search.html
{% extends 'layout.html' %}
{% block content %}
<form action="" class="form-inline mt-4" method="POST">
{{ form.hidden_tag() }}
<div class="form-group">
{{form.search(class='form-control', placeholder= 'Enter term to search')}}
{{form.submit(class='btn btn-outline-primary')}}
</div>
</form>
{% endblock %}
请参见this