Adding StringField dynamically in the client side form using a add button for receiving array input with WTForms

Viewed 21

So, the scenario is : I am trying to receive multiple blog links using a form. The user will press an Add button and a new string field will be generated. All the blog links will be then stored as an array in the database. I am trying to using FieldList and StringField to do that. My 'app.py'

class BlogForm(FlaskForm):
    blog_link = FieldList(StringField('blog'), min_entries=1, max_entries=10)

@app.route('/', methods=['GET', 'POST'])
def index():
    forms = BlogForm()
    if request.method == 'POST':
        #what should I write here to print the array from frontend form

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

form.html

<body>
    <form method="POST" action="/" id="test">
        <div id="dtest">        
            {{ form.blog_link }}
        </div>
        <input type='submit' value='submit'>
    </form>

<form name="form">
<input type="button" onclick="addInput()" name="add" value="Add input field" />
</form>

<script>
    var fields = 1;
    function addInput() {
        if (fields <= 10) {
            document.getElementById('dtext').innerHTML += "<input type='text' name="blog_link-0" /><br>";
            fields += 1;
        } else {
            document.getElementById('dtext').innerHTML += "<br />Only 10 upload fields allowed.";
            document.form.add.disabled = true;
        }
    }
</script>
</body>

Now, Can the addInput() be used to add input field ? How to catch the multiple blog_link values from the POST request in the app.py and print as an array?

0 Answers
Related