0

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

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 ? 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 ?

1 Answer 1

1

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

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

<script>
    populateForm('{{user.username}}','{{user,description}}');
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

thank you. Its better to see code for people who run to the same problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.