简体   繁体   中英

How to create a dynamic form with flask without WTForms

What I am trying to do is create a form that is automatically generated and then the values from that form are then used to proceed in the program. Currently to generate my form I am using this function

real_names=["Jason","Casandra"] this portion of the code is not static it is generated with the names of the previous part of the form.

     form = """
            <h2>What fields do you want your employee's on?:</h2>
            <dl>
            """
            def form_creator(name):
                            print name
                            dt = "<dt>"
                            dt_1 = dt+name.title()+":"
                            dt_kill = "</dt>"
                            input_basic_1 = '''<input name="''' 
                            input_basic_2 = """" size="1"> </input>"""
                            generated_input = dt_1+ input_basic_1 + name.lower() + input_basic_2+dt_kill
                            # flash(generated_input)
                            return generated_input
    for i in real_names:
                print ("\n\n"+i+"\n\n")
                form += form_creator(i)

return render_template('assign_score_b.html',form=form)

The HTML code is

{% extends "assign.html" %}
{% block content %}

<form method="POST">
   {{form|safe}}
</form>

{% endblock %}

Now after I generate the form and then get the varibles from the user I would like to process the form but I cannot seem to figure out how to get the values to be checked. What I was trying to do for the answers was

answers = []
for i in real_names:
    testable_var = request.form[i]
    try:
        int(testable_var)
    except:
        flash("Please submit an number not a letter")
    answers.append(testable_var)

but when I was trying to do this I got a error request. Using WTForms is NOT an option Your help will be very appreciated Thank you!

your code will work but you made one small crucial mistake. So your names are "Jason" and "Casandra" but the names of your form are "jason" and "casandra" The names themselves are capitalized but the form values aren't! Your code will work if you lower the variable i you can do this simply with string manipulation all you have to do is add on .lower() to your variable therefore your code would look like this:

for i in real_names:
    testable_var = request.form[i.lower()]
    try:
        int(testable_var)
    except:
        flash("Please submit an number not a letter")
    answers.append(testable_var)

now your code will work!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM