【问题标题】:Passing data to multiple forms in flask-wtforms将数据传递给flask-wtforms中的多个表单
【发布时间】:2019-10-23 02:28:57
【问题描述】:

考虑一下:

{% for user in users.query.all() %}
     <tr>
         <form method='POST' action="">
             <td>{{form.username}}</td>
             <td>{{form.description}}</td>
             <td>{{form.submit(value="Update")}}</td>
         </form>
     </tr>
{% endfor %}

这将为每个用户创建一个我可以更新的小表单,我想用当前数据库数据填充这些表单

我在路由文件中尝试做的事情:

@app.route("/Users")
def listUsers():
    users = Users
    form = UserForm()
    if request.method == 'GET':
        for user in users.query.all():
            form.username.data = user.username
            form.description.data = user.description
    return render_template('Users.html', users=users, form=form)

这导致最后一个用户的数据填充所有表单,我该如何解决这个问题? 我正在考虑为与用户匹配的每个表单分配一个 id,但我如何能够发送动态数量的表单?

【问题讨论】:

    标签: python flask flask-wtforms


    【解决方案1】:

    我花了一段时间,但我找到了解决办法,如果其他人有同样的问题,我会发布:

    我使用了 javascript ... 创建了一个函数并在 for 循环中调用它,为我填充了字段

    function populateForm(username,description){
        var form = document.getElementById('form id here');
        form.nextElementSibling.value = username;
        form.nextElementSibling.nextElementSibling.textContent = description;
    }
    

    请注意,我将 value 用于输入字段,将 textContent 用于文本字段,然后在 for 循环中添加了一个脚本标记

    <script>
        populateForm('{{user.username}}','{{user,description}}');
    </script>
    

    【讨论】:

    • 谢谢。最好为遇到相同问题的人查看代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    • 2017-07-15
    • 1970-01-01
    相关资源
    最近更新 更多