首页 > 解决方案 > Html form with flask - problem with passing table values to CSV file

问题描述

I'm new to python and hoping that someone on this forum could help me solving my problem.

In the form.html file I have a table called myTable where multiple rows can be added/deleted. What I'm trying to achieve is to capture all the possible values for each row added in this table and save it to output.csv file.

Desired output.csv:

requestPhoneNr    requestTopic    requestDescription requestOriginator 
 +615331234       Hello World      This is a test.       John Doe
 +1800324567      Greetings!!!     My test description.   Ana Doe
  ...

My problem: If there is more than one row added in myTable (form.html) only values for the first row are saved to output.csv instead of all the values from multiple rows. Could someone help me getting this right? Thanks!

myform.py

from flask import Flask, render_template, request
import csv


app = Flask(__name__)

@app.route('/')
def myForm():
   return render_template('form.html')

@app.route('/steptwo',methods = ['POST', 'GET'])
def steptwo():
   if request.method == 'POST':

        requestPhoneNr = request.form['requestPhoneNr']
        requestTopic = request.form['requestTopic']
        requestDescription = request.form['requestDescription']
        requestOriginator = request.form['requestOriginator']

        fieldnames = ['requestPhoneNr', 'requestTopic', 'requestDescription', 'requestOriginator']


        with open('output.csv','w') as inFile:
            writer = csv.DictWriter(inFile, fieldnames=fieldnames)

            # writerow() will write a row in your csv file
            writer.writerow({'requestPhoneNr': requestPhoneNr, 'requestTopic': requestTopic, 'requestDescription': requestDescription, 'requestOriginator': requestOriginator})

        return 'Thanks for your input!'



if __name__ == '__main__':
   app.run(debug = True)

form.html:

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <body>

      <form action = "http://localhost:5000/steptwo" method = "POST" id='myForm'>
         <p>ID <input type = "text" name = "id" /></p>
         <p>Name <input type = "text" name = "name" /></p>
         <p>Email <input type = "text" name = "email" /></p>
         <p>Website <input type ="text" name = "website" /></p>
         <p>



<table id="myTable" style="border: 1px solid black">
<th>requestPhoneNr</th><th>requestTopic</th><th>requestDescription</th><th>requestOriginator</th><th></th>
    <tr>
        <td>
            <input type="text" name="requestPhoneNr" class="requestPhoneNr" />
       </td>
        <td>
            <input type="text" name="requestTopic" class="requestTopic" />
        </td>
                <td>
            <input type="text" name="requestDescription" class="requestDescription" />
        </td>
        <td>
            <input type="text" name="requestOriginator" class="requestOriginator" />
        </td>
        <td>
            <input type="button" value="Delete" />
        </td>
    </tr>
</table>
<p>
    <input type="button" value="Insert row">
</p> 
<script>
$('#myTable').on('click', 'input[type="button"]', function () {
$(this).closest('tr').remove();
})
    $('p input[type="button"]').click(function () {
     $('#myTable').append('<tr><td><input type="text" name="requestPhoneNr" class="requestPhoneNr" /></td><td><input type="text" name="requestTopic" class="requestTopic" /></td><td><input type="text" name="requestDescription" class="requestDescription" /></td><td><input type="text" name="requestOriginator" class="requestOriginator" /></td><td><input type="button" value="Delete" /></td></tr>')
});
</script>
</p>

     <p><input type = "submit" value = "submit" /></p>
  </form>
      <script>
$('#myForm').submit((e) => {
    e.preventDefault();

    var items = [];
    $('#myTable tr').each((i, el) => {
        var item = {};

        var inputs = $(el).find("input").each((i, inputEl) => {
            if (inputEl.type != "text") {
                return;
            }

            var name = $(inputEl).attr("name");
            var val = $(inputEl).val();
            item[name] = val;
        });

        items.push(item);
    });

    // remove empty object made from table header
    items = items.filter(i => Object.keys(i).length != 0);

      $.ajax({
        url: e.target.action,
        crossDomain: true,
        method: e.target.method,
        contentType: "application/json",
        data: items,
        headers: {
              "accept": "application/json",
              "Access-Control-Allow-Origin":"*"
          }
        success: function () {
            // TODO: do success behaviors
        }
    });
});
    </script>
       </body>
    </html>

@Raffy Alcoriza I'm trying to include your answer below into my form.html. However, now when I press on 'submit' button nothing happens. I checked in Web Inspector and received the following errors:

enter image description here

enter image description here

Would you be able to tell what am I doing wrong? (also, I'm assuming that there are no changes needed in myform.py) thanks!

标签: pythonhtmlpython-3.xformsflask

解决方案


您可能需要覆盖您的提交按钮以获取所有行并在提交之前先将它们编译成一个项目数组。

$('#myForm').submit((e) => {
    e.preventDefault();

    var items = [];
    $('#myTable tr').each((i, el) => {
        var item = {};

        var inputs = $(el).find("input").each((i, inputEl) => {
            if (inputEl.type != "text") {
                return;
            }

            var name = $(inputEl).attr("name");
            var val = $(inputEl).val();
            item[name] = val;
        });

        items.push(item);
    });

    // remove empty object made from table header
    items = items.filter(i => Object.keys(i).length != 0);

    $.ajax({
        url: e.target.action,
        method: e.target.method,
        contentType: "application/json",
        data: items,
        success: function () {
            // TODO: do success behaviors
        }
    });
});

请务必将name属性添加到动态生成的表行中,与之前的相同:

$('p input[type="button"]').click(function () {
    $('#myTable').append(`
        <tr>
            <td>
                <input type="text" name="requestPhoneNr" class="requestPhoneNr" />
            </td>
            <td>
                <input type="text" name="requestTopic" class="requestTopic" />
            </td>
            <td>
                <input type="text" name="requestDescription" class="requestDescription" />
            </td>
            <td>
                <input type="text" name="requestOriginator" class="requestOriginator" />
            </td>
            <td>
                <input type="button" value="Delete" />
            </td>
        </tr>`)
});

最后,您的 Flask 应用程序应该通过response.data.


推荐阅读