1.准备视图函数search()
1 # 模糊查找 2 @app.route(‘/search‘, methods=[‘GET‘, ‘POST‘]) 3 def search(): 4 qu = request.args.get(‘q‘)
2.修改base.html 中搜索输入框所在的
1 <form class="navbar-form navbar-left" role="search" action="{{ url_for(‘search‘) }}" method="get"> 2 <div class="form-group"> 3 <input type="text" class="form-control" placeholder="搜索" required name="q"> 4 </div> 5 <button type="submit" class="btn btn-default">搜索</button> 6 </form>
3.完成视图函数search()
1 # 模糊查找 2 @app.route(‘/search‘, methods=[‘GET‘, ‘POST‘]) 3 def search(): 4 qu = request.args.get(‘q‘) 5 query = Question.query.filter( 6 or_( 7 Question.title.contains(qu), 8 Question.detail.contains(qu), 9 ) 10 ).order_by(‘-creat_time‘).all() 11 context = { 12 ‘user‘: ‘huadahua‘, 13 ‘title‘: ‘大家好”‘, 14 ‘time‘: ‘2017-09-29‘, 15 ‘detail‘: ‘这是我的python‘, 16 ‘questions‘: query 17 } 18 return render_template(‘index.html‘, **context)
search结果: