1

I am trying generate a checklist in a html table from a json file using BooleanField() So far I have it without using wtforms:

from view.py

from app import app

from flask import render_template

json_data = [{'Description':'Red', 'id':'f1'},{'Description':'Green', 'id':'f2'},{'Description':'Blue', 'id':'f3'}]


@app.route('/taggs', methods = ['GET', 'POST'])
def taggs()
    return render_template('taggs.html', jdata = json_data)

from taggs.html

<form role="form" method= "post">
<table id='ctable'>
    <thead>
    <tr>
        <th data-field="Description"></th>
        <th data-field="Selection"></th>
    </tr>
    </thead>
<tbody>

</tbody>
    {% for i in jdata %}
    <tr>
        <td>{{ i.Description }}</td>
        <td><input type ="checkbox" id = "{{ i.id }}"></td>
    </tr>
    {% end for%}
</table>
</form>

Is there a way of generating form fields using a list in wtforms? or do I have to create a class and declare each variable in the list?

1 Answer 1

2

Yes, you can do this dynamically in your view function.

The docs have an example of this, which you can adapt along the lines of:

from flask import render_template, request
from flask_wtf import Form
from wtforms import BooleanField

json_data = [{'Description':'Red', 'id':'f1'}, 
             {'Description':'Green', 'id':'f2'}, 
             {'Description':'Blue', 'id':'f3'}]


@app.route('/taggs', methods = ['GET', 'POST'])
def taggs():
    class CustomForm(Form):
        pass

    for item in json_data:
        setattr(CustomForm, item["id"], 
                BooleanField(item["description"], id=item["id"]))

    form = CustomForm(request.form)

    return render_template('taggs.html', form=form)
Sign up to request clarification or add additional context in comments.

2 Comments

@PJ_Santoro what do you put in the jinja 2 loop?
if you use Flask-Bootstrap you can use the wtf.quick_form() macro or loop through the items {% for element in form %}{{ element.label }}{{ element() }}... like the wtforms docs. mostly depends on your data model and how you'd like it to render.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.