有没有办法从flask中的多个表单中获取表单数据?

问题描述

@app.route('/',methods = ['POST'])
def user_rating():
    for i in form_value['rating']:
        print(request.form.get(str(i)))
        
    return("Thank You")

我尝试了各种方法,但都不起作用。有没有办法遍历表单名称获取它们的值 以上是我正在处理的代码,希望通过一个按钮从多个表单中获取数据。但只能从表单中获取一个值。

HTML 代码

       <tbody>
            {% for record in records %}
            <tr>
                {% for col in colnames %}
                <td>                 
                {% if (col != 'poster_link') and ( col != 'rating' ) %}

                    {{ record[col] }}
                
                {% endif %}                    
                
                 <!--Movie Poster-->  
                {% if col == 'poster_link' %}
                
               <img src={{ record[col] }} style="width:150px">
                
               {% endif %}
               <!--end of Movie Poster-->  
               
                <!--form rating-->
                {% if col == 'rating' %}

                **<form method="post" id="FORMID" action="{{url_for('user_rating')}}">
                    <input type="text" name= {{ record[col] }} placeholder="Give rating 1 to 5" >
                 </form>**
                 

                {% endif %}
                <!--end of form rating-->
                </td>
                {% endfor %}
            </tr>
            {% endfor %}
            
        </tbody>
    </table>

    <button type="submit" form="FORMID" value="Submit">Submit</button>

得到这样的输出

1
None
None
None
None
None
None
None
None
None

解决方法

这是不可能的,因为用户只能在一个页面上提交一个表单。无论提交哪种表单,您的后端代码都会读取该表单。你应该做的是:

  1. 每次输入更改时使用 AJAX 发出请求,或
  2. 只使用一种形式

根据您的代码,似乎只使用一种形式会更容易。所以这样的事情会起作用:

<form method="post" id="FORMID" action="{{url_for('user_rating')}}">
    <table>
       <tbody>
            {% for record in records %}
            ...

                
                    <input type="text" name= {{ record[col] }} placeholder="Give Rating 1 to 5" >
                 

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

    <button type="submit" form="FORMID" value="Submit">Submit</button>
</form>