FlaskWTF same form on every view / page

吃可爱长大的小学妹 提交于 2020-06-01 05:09:26

问题


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.

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 excerpt:

class Search(FlaskForm):
    search_query = StringField('Search for ...')
    submit = SubmitField('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?


回答1:


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' %}

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

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)

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>


来源:https://stackoverflow.com/questions/62094647/flaskwtf-same-form-on-every-view-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!