Search code examples
flaskjinja2flask-sqlalchemy

Making Post request in a flask template for loop


I am making a post request in a flask template for loop where I am passing the id from each of the element in the for loop back to the endpoint. I want to be able to receive the id of the element I clicked from the frontend. The click work but a wrong element (not the id that I clicked) is being sent to the endpoint.

{% for data in profile %}
              <tr>
                <td>{{data.id}}</td>
                <td>{{data.email}}</td>
                <td>{{data.full_name}}</td>
                <td>{{data.given_name}}</td>
                <td>{{data.created_at | format_datetime('full')}}</td>
                <td>
                  <form method="post" id="is_admin">
                    <input hidden name="profile_id" value="{{data.id}}" />
                    <input type="checkbox" name="toogle_off" id="{{data.id}}"
                    onchange="document.getElementById('is_admin').submit()" {{
                    "checked" if data.is_admin == True }} /> {{data.is_admin}}
                  </form>
                </td>
              </tr>
              {% endfor %}

When I click any of the profile, it I got a ID. it returns a particular element all the time. The profile is from a database query.

I have tried setting the id for the input submitting the data.


Solution

  • You create multiple forms with the same id: id="is_admin" and with getElementById('is_admin') selector you submit only the first form every time. You need to create unique ids form the forms/selectors as well, e.g.:

    {% for data in profile %}
      <tr>
        <td>{{data.id}}</td>
        <td>{{data.email}}</td>
        <td>{{data.full_name}}</td>
        <td>{{data.given_name}}</td>
        <td>{{data.created_at | format_datetime('full')}}</td>
        <td>
          <form method="post" id="is_admin_form_{{data.id}}">
            <input hidden name="profile_id" value="{{data.id}}" />
            <input type="checkbox" name="toogle_off" id="{{data.id}}"
              onchange="document.getElementById('is_admin_form_{{data.id}}').submit()" {{
              "checked" if data.is_admin == True }} /> {{data.is_admin}}
          </form>
        </td>
      </tr>
    {% endfor %}