首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用Flask & JINJA2让python从动态表中检索用户输入的数据

如何使用Flask & JINJA2让python从动态表中检索用户输入的数据
EN

Stack Overflow用户
提问于 2018-07-23 04:04:50
回答 1查看 768关注 0票数 1

我正在构建一个Flask应用程序,其中包括一个表格,用户可以在其中更改单元格,并将这些更改‘应用’,例如在数据库中更新。

图片如下

我在获取通过表单提交的数据时遇到了问题。

行数是动态的,并且依赖于列表中Id的数量。

这是我的html --抱歉,我还在学习。

代码语言:javascript
复制
                            <tbody> 
                            <form method="post" name="productCost">
                        {% for n in range(name_list | length) %}
                            <tr> 
                                <th scope="row" >{{name_list[n]}}</th> 
                                <td>{{ID_list[n]}}</td> 
                                <td id="cost{{n}}">${{cost_list[n]}}</td> 
                                <td>---</td>
                                <td id="changes{{n}}"><button onclick="costChanges{{n}}()">Edit</button></td> 
                            </tr> 
                        <script>
                            function costChanges{{n}}() {
                                document.getElementById("cost{{n}}").innerHTML = "<input placeholder='{{cost_list[n]}}' name={{ID_list[n]}}>";
                                document.getElementById("changes{{n}}").innerHTML = "<button onclick='applyChanges{{n}}()' type='submit'>Apply</button><button onclick='cancelChanges{{n}}()'>Cancel</button>";

                            }
                            function applyChanges{{n}}() {
                                docuemnt.getElementById("cost{{n}}").innerHTML = document.forms["productCost"]["{{ID_list[n]}}"]
                            }
                            function cancelChanges{{n}}() {
                                document.getElementById("cost{{n}}").innerHTML = "{{cost_list[n]}}";
                                document.getElementById("changes{{n}}").innerHTML = "<button onclick='costChanges{{n}}()'>Edit</button>";

                            }
                        </script>
                        {%endfor%}
                    </form>
                        </tbody>

下面是我的python/flask代码:

代码语言:javascript
复制
app.route('/expenses', methods=['GET', 'POST'])
def expenses():
    if 'email' not in session:
        return redirect(url_for('login_now'))

    list_of_product_dicts = get_name_id()
    name_list = []
    asin_list =[]
    cost_list=[]
    for p in list_of_product_dicts:
        name_list.append(p['name'])
        id_list.append(p['id'])
        cost = get_landing_cost(p['id'])
        cost_list.append(cost)

    if request.method == 'POST':
            print(request.form['name']) 
    return flask.render_template('expenses.html', name_list = name_list, id_list=id_list,
        cost_list=cost_list)

我需要python来识别所做的更改,并将其存储在一个变量中。这是为了在数据库中更新它--但我不需要数据库代码方面的帮助。我只需要帮助python抓取已更改的单元格,并识别它在哪一行。

EN

回答 1

Stack Overflow用户

发布于 2018-07-23 05:29:54

ajax中使用jquery会更简单一些。后者使您能够通过与后端脚本通信来更新数据库,从而动态更新表。

jquery干净利落地处理Apply、Cancel和Edit按钮功能,并通过ajax与后端通信

tables.html

代码语言:javascript
复制
<html>
  <body>
   <table>
   <tr>
     <th>ID</th>
     <th>Cost</th>
     <th>Effective Date</th>
     <th>Make Changes</th>
   </tr>
  {%for row in data%}
  <tr>
    <td>{{row.id}}</td>
    <td class='cost{{row.rowid}}'>{{row.price}}</td>
    <td>{{row.date}}</td>
    <td>
      <div id='options{{row.rowid}}'>
        <button id='mutate{{row.rowid}}'>Edit</button>
      </div>
    <td>
  </tr>
  {%endfor%}
 </table>
 </body>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
 <script>
 $(document).ready(function() {
  $("div[id^='options']").on('click', 'button', function(){
   var the_id = this.id.match('\\d+');
   var the_type = this.id.match('[a-zA-Z]+');
   if (the_type == "mutate"){
    $('#options'+the_id).html('<button id="cancel'+the_id+'">Cancel</button>\n<button id="apply'+the_id+'">Apply</button>');
    var current_cost = $('.cost'+the_id).text();
    $('.cost'+the_id).html('\n<input type="text" class="newval'+the_id+'" value="'+current_cost+'">')
   }
   else if (the_type == 'cancel'){
    $('#options'+the_id).html('<button id="mutate'+the_id+'">Edit</button>');
   }
   else{
    var value = $(".newval"+the_id).val();
    $.ajax({
          url: "/update_cell",
          type: "get",
          data: {newval: value, rowid:the_id},
          success: function(response) {
            $('.cost'+the_id).html(value);
            $('#options'+the_id).html('<button id="mutate'+the_id+'">Edit</button>');
          },
          error: function(xhr) {
            //Do Something to handle error
          }
       });
     }
   });
 });
 </script>
</html>

然后,创建应用程序和路由:

代码语言:javascript
复制
import flask, sqlite3, collections
app = flask.Flask(__name__)

@app.route('/', methods=['GET'])
def home():
  dummy_data = [['hvVlNnAW', '$6.00', '--'], ['UqBzqLho', '$10.00', '--'], ['tuEdqldI', '$3.00', '--'], ['MIHLFWDS', '$1.00', '--'], ['rUnjpHiJ', '$8.00', '--'], ['lHVHxgZF', '$1.00', '--'], ['nFfaHkHj', '$3.00', '--'], ['rRWqXqVh', '$8.00', '--'], ['rdzCRozr', '$4.00', '--'], ['MGojGbtW', '$9.00', '--']]
  #substitute dummy_data with a database query
  product = collections.namedtuple('product', ['id', 'price', 'date', 'rowid'])
  return flask.render_template('tables.html', data = [product(*a, i) for i, a in enumerate(dummy_data, 1)])

@app.route('/update_cell')
def update_row():
   new_val = flask.request.args.get('newval')
   prod_id = int(flask.request.args.get('rowid[]'))
   #commit new_val to database
   return flask.jsonify({'success':True})

现在,在'/update_cell'中,您有了新的价格值和产品行id,它告诉您要更新哪一个sqlite行的价格。请注意,在home中,由enumerate获得的行id对应用程序至关重要,因为它使jquery能够知道要更新哪些表和sqlite行。

演示:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51468834

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档