Solution 1 :

Yes it probably easiest to define your own render_template function:

def render_template_form(template, **kwargs):
    quicksearch = QuickSearchForm()
    return render_template(template, quicksearch=quicksearch, **kwargs)

Then just replace in your own functions:

def home():
    return render_template_form('index.html')

Problem :

I am trying to implement a WTForms search feature on every page of my Flask website. I would like avoid creating the form for every Python function.

At the moment, I generate the QuickSearchForm() for every function and pass it into every page. However, I would much rather define it once and have it load onto every webpage automatically.

Is this possible with WTForms?

Here is a snippet of the current Python code:


class QuickSearchForm(FlaskForm):
    name = StringField(
        render_kw={"placeholder": "Quick Search"}


def home():
    quicksearch = QuickSearchForm()
    return render_template('index.html', quicksearch=quicksearch)

def content():
    quicksearch = QuickSearchForm()
    return render_template('content.html', quicksearch=quicksearch)

@bp.route('/quick_search', methods=('GET', 'POST'))
def quick_search():
    quicksearch = QuickSearchForm()
    if request.method == 'POST':
        return render_template('results.html', results=results, quicksearch=quicksearch)
    return render_template('home.html', quicksearch=quicksearch)

And the HTML for the form:

<form method="POST" action="{{ url_for('home.quick_search') }}">
    <fieldset class="form-field">
        {{ }}
        {% if %}
        <ul class="errors">
            {% for error in %}
            <li>{{ error }}</li>
            {% endfor %}
        {% endif %}
    {{ quicksearch.hidden_tag() }}

I would rather define the quicksearch in the __init__ and be done.