带烧瓶的HTML表单-将表值传递到CSV文件的问题 [英] Html form with flask - problem with passing table values to CSV file

查看:74
本文介绍了带烧瓶的HTML表单-将表值传递到CSV文件的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,希望这个论坛上的人可以帮助我解决问题.

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

在form.html文件中,我有一个名为 myTable 的表,可以在其中添加/删除多行.我想要实现的是捕获此表中添加的每一行的所有可能值,并将其保存到output.csv文件.

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.

所需的output.csv:

Desired output.csv:

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

我的问题:如果myTable(form.html)中添加了多个行,则仅将第一行的值保存到output.csv中,而不是多行中的所有值.有人可以帮我解决这个问题吗?谢谢!

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我正在尝试将下面的答案包含在我的form.html中.但是,现在当我按下提交"按钮时,什么也没有发生.我检查了Web Inspector并收到以下错误:

@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:

您能告诉我我做错了吗? (另外,我假设myform.py中不需要进行任何更改)谢谢!

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!

推荐答案

您可能需要覆盖提交"按钮以获取所有行,然后在提交之前先将它们编译为项目数组.

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
        }
    });
});

请确保将name属性添加到动态生成的表行中,与以前的相同:

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

最后,您的Flask应用应通过response.data接收整个项目列表中的数据.

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

这篇关于带烧瓶的HTML表单-将表值传递到CSV文件的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆