嘿,我是stackoverflow的新手,所以如果我犯了任何错误,请原谅我正在尝试向我的应用程序添加搜索表单,但是即使我提供了数据库中存在的值,它也始终显示没有这样的数据。我使用python作为后端,并使用flask作为框架。
@app.route("/search",methods=['GET', 'POST'])
def search():
form = Search(request.form)
if form.validate_on_submit():
city = form.city.data
blood = form.blood.data
results = User.query.filter_by(blood_type=blood,city=city).all()
if not results:
flash('No results found!')
else:
return render_template('result.html',results=results)
return render_template('search.html',form=form)
这是表格
class Search(FlaskForm):
blood = StringField('Blood',validators=[DataRequired()])
city = StringField('City',validators=[DataRequired()])
submit = SubmitField('Search')
数据库表
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True,nullable=False)
email = db.Column(db.String(100), unique=True,nullable=False)
image_file = db.Column(db.String(20),nullable=False, default='default.jpg')
password = db.Column(db.String(60),nullable=False)
blood_type = db.Column(db.String(20), nullable=False)
phone_no = db.Column(db.String(20),nullable=False)
city = db.Column(db.String(30), nullable = False)
address = db.Column(db.Text,nullable=False)
post = db.relationship('Post',backref='author', lazy=True)
搜索页面
<div class="content-section">
<form method="POST" action="search">
{{ form.hidden_tag() }}
<fieldset class="form-group">
<div class="form-group">
{{ form.city.label(class="form-control-label") }}
{% if form.city.errors %}
{{ form.city(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.city.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.city(class="form-control form-control-lg") }}
{% endif %}
</div>
<div class="form-group">
{{ form.blood.label(class="form-control-label") }}
{% if form.blood.errors %}
{{ form.blood(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.blood.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.blood(class="form-control form-control-lg") }}
{% endif %}
</div>
</fieldset>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info") }}
</div>
</form>
</div>
结果
{% extends "layout.html" %}
{% block content %}
{% for results in results %}
<article class="media content-section">
<div class="media-body">
<a class="mr-2" href="#">{{ results.username }}</a>
<a class="mr-2" href="#">{{ results.phone_no }}</a>
</div>
</article>
{% endfor %}
{% endblock content %}