R
R
RaymanPy2020-06-02 00:13:23
Python
RaymanPy, 2020-06-02 00:13:23

How to make a Cycle from FLASK_WTF Forms?

Let's say: if I enter data into the second form and click on the Submit of the second form, but for some reason the loop thinks that I click on the Submit of the first form and the user.value data is written there.
Is it even possible to use a form class to create multiple form objects?

class TestForm(FlaskForm):
    param1 = StringField('param1')
    param2 = StringField('param2')
    submit = SubmitField('start')

@app.route('/'.methods=['GET','POST'])
def index():
    users = session.query(User).filter(User.id!=None).all()
    forms = [TestForm for i in range(len(users))]
    
    for form,user in zip(forms,users):
        if form.validate_on_submit():
            user.value = int(form.param1.data) + int(form.param2.data)
            session.add(user)
      session.commit()
            redirect('/')
   return render_template('index.html',forms=forms,users=users,count=len(forms))

{% block content %}
<table class="table table-bordered table-dark">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Модель</th>

      <th scope="col">количнсто</th>
      <th scope="col">бла бла бла</th>
    </tr>
  </thead>
  <tbody>
  	{% for i in range(count) %}
  	
    <tr>

      <th scope="row"> {{ users[i].id }} </th>
      <td>{{ users[i].name }}</td>

    <form action="", method="post"> 
      {{ forms[i].hidden_tag() }} 
      <td>
      
       {{ forms[i].param1(class="form-control") }}
      </td>

      <td>
      
       {{ forms[i].param2(class="form-control") }}

      </td>

      <td>
        {{ forms[i].submit(class="btn btn-primary") }} 
      </td>
      </form>
      <td>
       {{ users[i].value }} 
      </td>
    </tr>

   	{% endfor %}
    
  </tbody>
</table>

{% endblock %}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
RaymanPy, 2020-06-02
@RaymanPy

Found a similar question on StackOverflow.
And so the matter is that in POST-request it is not specified from what form the data came.
To solve the problem, you need to separate GET and POST handlers:
Here is the answer itself

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question