首页 > Flask分页后,form表单无法传值,要怎么解决?

Flask分页后,form表单无法传值,要怎么解决?

1、定义了一个搜索表单 form.py:

class SearchForm(Form):
    search_keyword = StringField('', validators = [DataRequired()])
    submit = SubmitField('Start Search')

2、定义路由函数 views.py:

出问题的地方: 可以通过 value = request.form.get('search_keyword')取到表单提交的值; 在分页后,点击“下一页”,这个表单就被清空了,没有search_keyword这个值了,怎么都取不到,导致分页的其它页就无法根据search_keyword显示内容了。这个要怎么解决呢?

@app.route('/search', methods=['POST', 'GET'])
def search():
    form = SearchForm():
    keyword = form.search_keyword.data

    page = request.args.get('page', 1, type=int)
    value = request.args.get('keyword')

    if form.validate_on_submit():
        pagination = Post.query.filter(Post.content.like(keyword))paginate(
            page, per_page=current_app.config['default'], error_out=False)

posts = pagination.items
return render_template('search.html', posts=posts, pagination=pagination, form=form, value=value)

3、页面 search.html

<div class="list">
    {% include 'list.html' %}
</div>
{% if pagination %}
    <div class="pagination">
    {{ macros.pagination_widget(pagination, '.search', value=value)}}
    </div>
{% endif %}

post验证之后跳转路由,显式作为路由参数,看看各网站搜索url就明白了。
这样之后post验证就防君子不防小人。


是否考虑不使用post,而是使用

/aaaaa?search=keyword
value = request.args.get('search')

同样的回答,使用两个视图

def search():
    form = DoSearchForm()
    if form.validate_on_submit():
        search = form.search.data
        return redirect(url_for('search_content', search=search))
    return render_template('搜索页')


def search_content():
    page = request.args.get('page')
    search = request.args.get('search')
    if not search:
        return redirect(url_for('search'))
    else:
        posts = Post.query.filter(Post.content.like(search)).paginate(
            page,
            per_page=current_app.config['default'],
            error_out=False)
    return render_template('显示内容页', posts=posts)

或者使用一个函数也行

# 大概就是这么个情况
def search():
form = DoSearchForm()
page = request.args.get('page', type=int)
search = request.args.get('search')
if form.validate_on_submit() and request.method == 'POST':
    search = form.search.data
    return redirect(url_for('forums.search', search=search, page=1))
else:
    topics = Topic.query.filter(Topic.content.like(search)).paginate(
        page,
        per_page=current_app.config['PER_PAGE'],
        error_out=False)
    return render_template('forums/search.html', topics=topics,form = form)

可以考虑把search keyword放在g里?

【热门文章】
【热门文章】