Search code examples
pythonflaskflask-wtforms

Flask Create Form from Dictionary


Recently started up with Flask. Currently, I have a program that searches through a docx file for {{}} tags and adds them to a dictionary that ends up looking like the below.

{
  ‘{{name}}’:’John’,
  ‘{{address}}’:’’,
  ‘{{zip}}:’’
}

I would like a page that displays the key field names, and a form for entry for each field. The values should be pre-populated if there is a value ie John. User should be able to change this. Obviously, blank values would be blank awaiting user input.

The length of the dictionary will differ (could be 5, could be 20 field names.)

How would one go about solving this? Not sure if this would be referred to as dynamic form generation?

Thanks


Solution

  • So I was overthinking this and trying to force a square peg into a triangular hole with WTForms.

    The solution was simple. Utilize jinja2 templating engine to create form and input elements for each key pair value in the dictionary.

    <!DOCTYPE html>
    <html>
    <link rel= "stylesheet" type= "text/css" href="{{ url_for('static',filename='stylesheets/style.css') }}" />
    {% block content %}
    <h1>Enter your values below</h1>
    <form id = "form1" action="" method="post" novalidate>
        {{ form.hidden_tag() }}
        {% for line in form.lines %}
            <label>{{line}}:</label> <input type="text" name=values>
        {% endfor %}
        <input type="submit" value = "Submit">
    </form>
    {% endblock %}
    </html>