How to submit data from a Search Form within the base.html of a Flask app?

Viewed 484

I'd like to have a search form in my navbar which is 'included' in my base.html template. This means the search bar can be filled out and submitted from any of my templates that extend from base.html. The results will be displayed on my index page, so once the form is submitted, the form data should be redirected to my index route and eventually passed to the index.html template.

I think this might be possible with context processing, by creating a @app.context_processor function, but I haven't found a lot of documentation on it- particularly using flask. Can context processing be used for this kind of thing or is it more for returning global variables back into the template?

If it can be done, what do I need to do to set it up? Any help appreciated

1 Answers

The action attribute in the form tag can define which view to post the data to in the search form. The view itself can then handle the data and redirect.

# base.html
<form action="{{ url_for('index') }}" method="post">
...
</form>
# view.py
@route('/', methods=['GET', 'POST']
def index():
    if request.method == 'POST':
        # handle form data here
        return render_template('index.html', form_data=data)
Related