1

I don't know how can I improve this code, I'm trying to insert multiple data with same field with different values. Can someone improve my code?

<form action="/submits/ method="POST">

    <input type="text" name="book" value="Divergent">
    <input type="text" name="author" value="Veronica Roth">

    <input type="text" name="book" value="Allegiant">
    <input type="text" name="author" value="Veronica Roth">

    <input type="text" name="book" value="Inferno">
    <input type="text" name="author" value="Dan Brown">

    <input type="submit" value="Submit">

</form>

@app.route('/submits/', methods = ['POST'])
def books():
    if method == "POST":
        BOOK = request.form['book']
        AUTHOR = request.form['author']
        stmt = "INSERT INTO shelf (book_column, author_column) VALUES (%s, %s)"
        c.executemany(stmt, (BOOK, AUTHOR))
        conn.commit()
3
  • 1
    First of all remove the typo here BOOK = request.form['book] you need one more single quote after book. Commented Sep 1, 2017 at 13:28
  • 0decimal0 I'm not really sure if my code will really work, is it? I'm new to Python and Flask, may you consider this problem. Commented Sep 1, 2017 at 13:34
  • are you having errors executing this? Commented Sep 1, 2017 at 13:43

1 Answer 1

1

you can try use getlist:

if method == "POST":
    stmt = "INSERT INTO shelf (book_column, author_column) VALUES (%s, %s)"
    books = request.form.getlist('book')
    authors = request.form.getlist('author')
    for i, book in enumerate(books):
        c.executemany(stmt, (book, authors[i]))
        c.commit()
Sign up to request clarification or add additional context in comments.

Comments

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.