简体   繁体   English

在flask-wtforms中将数据传递给多个forms

[英]Passing data to multiple forms in flask-wtforms

Consider this:考虑一下:

{% 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 %}

For each user this will create a small form that I can update, I want to populate these forms with current database data对于每个用户,这将创建一个我可以更新的小表单,我想用当前数据库数据填充这些 forms

What I tried to do in the routes file:我在路由文件中尝试做的事情:

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

This results in having the data of the last user populating all of the forms, how can I go about fixing this?这导致最后一个用户的数据填充了所有 forms,我该如何解决这个问题? I was thinking of assigning an id to each form that matchs the user, but how would I be able to send a dynamic number of forms?我正在考虑为与用户匹配的每个表单分配一个 ID,但我如何能够发送 forms 的动态编号?

It took me a while, but I got a work around, just gonna post it if anyone else has the same issue:我花了一段时间,但我得到了解决,如果其他人有同样的问题,我会发布它:

I used javascript... created a function and called it within the for loop which populated the fields for me我使用 javascript... 创建了一个 function 并在为我填充字段的 for 循环中调用它

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

note that I used value for input field and textContent for textfield, then inside the for loop i added a script tag请注意,我将 value 用于输入字段,将 textContent 用于文本字段,然后在 for 循环中添加了一个脚本标签

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM