Flask Create Form from Dictionary

Question:

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

Asked By: Mav

||

Answers:

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>
Answered By: Mav

hey did you create a Flaskform class in your app and then call this from from route ? I am trying to achieve the same creating the from on the fly like without creating any class based on the dictionary but got a jinja exception.

Answered By: bugraefendi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.