Html form with flask - problem with passing table values to CSV file

拟墨画扇 提交于 2020-04-30 09:24:36

问题


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:

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!


回答1:


You may need to override your submit button to get all of your rows and compile them first into an array of items before you submit.

$('#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
        }
    });
});

Be sure to add the name attribute to your dynamically generated table rows, same as with previous:

$('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>`)
});

Finally, your Flask app should receive the data as a whole list of items via response.data.



来源:https://stackoverflow.com/questions/61279577/html-form-with-flask-problem-with-passing-table-values-to-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!