在每个视图/页面上都使用相同的表格 [英] FlaskWTF same form on every view / page

查看:91
本文介绍了在每个视图/页面上都使用相同的表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Flask项目中,我已经配置了一个basepage.html Jinja模板,其他每个页面都继承自该模板. 在此basepage.html中,我希望在顶部有一个搜索栏,以便它也出现在从其继承的每个页面上.

in my Flask Project i have configured a basepage.html Jinja template every other page inherits from. In this basepage.html i want to have a Search bar at the top, so that it also appears at every page inheriting from it.

应该处理此搜索表单的输入(是最好的表单吗?) 通过路由功能search()我定义如下:

The input from this search form (is a form even the best way to do it?) should be processed by the routing function search() I defined as follows:

views.py

@app.route('/')
@app.route('/dashboard')
def dashboard():
    return render_template('Dashboard.html') #Dashboard.html inherits from basepage.html

@app.route('/search', methods=['GET' ,'POST'])
def search():
    search_query = #input from search-bar
    result = #get data matching search_query from database
    return render_template('Search.html', results = results) #Search.html extends basepage.html

forms.py摘录:

forms.py excerpt:

class Search(FlaskForm):
    search_query = StringField('Search for ...')
    submit = SubmitField('Search')

是否可以在每个页面上使用搜索"表单,所以当我在仪表板"表单顶部的栏中输入查询并按Enter时,search_query将由search()视图处理?

Is there a way i can have my Search form on every page, so when i enter my query in the bar at the top of the Dashboard form and press enter the search_query gets processed by the search() view?

推荐答案

只需在位于/templates/includes/my_searchbar.html的部分文件中或您要命名的文件中创建搜索栏模板代码,然后在基本模板中放置一个include指令即可无论您要在何处呈现搜索,都可以使用

Just create your searchbar template code in a partial file located at /templates/includes/my_searchbar.html or whatever you want to name it and then in your base template just place an includes directive wherever you want the search to render in, something like:

{% include 'includes/my_searchbar.html' %}

如果搜索栏包含在base中,而您所有其他模板都继承自base,则搜索将包含在所有页面中.

If the searchbar is included in base and all your other templates inherit from base, then search will be included on all pages.

您所有的路线也都需要包含Search()表单类,这样他们才可以访问该表单,因此您需要修改您的路线,例如:

All of your routes will also need to have the Search() form class included so they have access to the form, so you will need to modify your routes something like:

from app.forms import Search #if you defined Search in /app/forms.py

@app.route('/dashboard')
def dashboard():
    search_form = Search() #initialize an instance of the form
    return render_template('Dashboard.html', search_form=search_form)

然后,您可以在includes/my_searchbar.html部分中使用search_form来呈现表单.也许像这样:

Then you can use search_form in your includes/my_searchbar.html partial to render the form. Maybe something like:

<form class="form" method="post" role="form">
    {{ search_form.hidden_tag() }}
    {{ search_form.search_query }}
    {{ search_form.submit }}
</form>

这篇关于在每个视图/页面上都使用相同的表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆