简体   繁体   中英

getlist on flask

using the request.form.getlist in Flask, I only get the last value of a list. Here below the .py code and html related. If I suppress the following three lines, then I get the full list, but so doing I miss the headers of the html table rows.

<form action="{{ url_for('show_entries')}}" method=get>
<td width="50"><font size="2">{{ L }}</font></td>   
</form>

What should I do ? Thanks for any hint !

from flask import Flask, render_template, request, url_for

app = Flask(__name__)

data = [
('t', 0, 'a'),
('t', 0, 'b'),
('t', 0, 'c'),
('t', 0, 'd')
 ]

@app.route('/', methods=['GET', 'POST'])
def show_entries():
  entries=[]
  for (i,v) in enumerate(data):
     entries.append(data[i][2])
  return render_template('layout2.html', entries=entries)

@app.route('/get', methods=['GET', 'POST'])
def get_entries():
  cl1=[]
  cl1=request.form.getlist('cn')
  return render_template('test2.html', cl1=cl1)

if __name__ == "__main__":
   app.debug = True
   app.run()

The layout2.html file is:

<!DOCTYPE HTML>
<table>

{% for L in entries %}
<tr>
<form action="{{ url_for('show_entries')}}" method=get>
<td width="50"><font size="2">{{ L }}</font></td>   
</form> 
<form action="{{ url_for('get_entries')}}" method=post>
<td width=100 align=center><input type=text name=cn size=3 value=0.0></td>
</tr>
{% if loop.last==True %}
    </table>
    <br>
    <div ALIGN=left>
    <input type=submit value=Submit>
    </form>
    </div>
{% endif %}  
{% endfor %}

The test2.html is:

<!DOCTYPE HTML>
<div ALIGN="center">
<td width="50"><font size="2" face="verdana" color="red">OUTPUT=</font></td>
<form action="{{ url_for('get_entries')}}" method=get></form>
<td width="50"><font size="2" face="verdana" color="red">{{ cl1 }}</font></td>
</div>

The only direct descendants that a <tr> element can have are <td> and <th> elements. You can't have a <form> element in there.

Put your <form> tag inside of the <td> and it should work:

<td width="50">
    <form action="{{ url_for('show_entries')}}" method=get>
        <font size="2">{{ L }}</font>
    </form>
</td>

Also, your HTML is outdated:

  • The <font> tag is deprecated.

  • Similarly, the align attribute is also deprecated.

Style things with CSS.

You are opening multiple form elements but only closing one of them - this is probably causing the browser to only send over the last form - and hence only one value is being sent over. Wrap your form around the entire table instead (and remove the nested form) and getlist will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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