Search code examples
python-3.xformsflaskjinja2

How to generate a form based on a list in jinja2?


I have a list of tags pulled from a python list I want to used as checkboxes on flask form. The Jinja2 templates is

{% for tag in tags %}
{% set tagValue = tag %}
<input type="checkbox" name="tag-checks" value="{{ request.form.get('tagValue') }}"> {{ tagValue }}</input><br>
{% endfor %}

The python code section is :

@app.route('/tagfilter/', methods=('GET', 'POST'))
def tagfilter():
    tags=tm.listTags()
    if request.method == 'POST':
        for tag in tags:
            tagValues = request.form[tag]
        if not tags:
            flash('Tags are required!')
            return redirect(url_for('tagfilter'))
        notes=nm.listTaggedNotes(tagValues)
    else:
        notes=nm.listNotes()
    return render_template('tagfilter.html', notes=notes, tags=tags)

However the jinja2 template is not sending the selected boxes to the backend, the value None is passed.


Solution

  • The following example shows you the implementation of checkboxes in Jinja using a sequence. Using request.form.getlist() returns a list populated with the values of the 'value' attribute of all selected checkboxes.

    @app.route('/tagfilter/', methods=('GET', 'POST'))
    def tagfilter():
        tags = ('video', 'audio', 'book', 'magazine')
        if request.method == 'POST':
            print(request.form.getlist('tag-checks'))
        return render_template('tagfilter.html', **locals())
    
    {% for tag in tags -%}
    {% set tag_id = 'tag-checks-{0}'.format(loop.index0) -%}
    <div class="input-group">
        <input 
            type="checkbox" 
            id="{{ tag_id }}"
            name="tag-checks" 
            value="{{ tag }}" 
            {% if tag in request.form.getlist('tag-checks') %}checked{%endif -%} 
            />
        <label for="{{ tag_id }}">{{ tag }}</label>
    </div>
    {% endfor -%}