我的问题并不是那么严重,只是有点烦人。我有一个下拉菜单和一个值列表;但是,我的值会将自己重置为第一个选项,并且我希望它们保持用户选择它们的状态。
我从其他来源了解到,解决方案是使用getlist而不是get,但当我尝试这样做时,我得到了以下错误:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
我几乎没有使用flask和Jinga的经验。我猜这一定是值类型的问题,或者是我需要获取的某种类型的名称或值……老实说我也不知道。任何帮助都将不胜感激。
这是flask如何与request.form.get一起工作的video,这是我为特定的html视图和我请求数据的应用程序片段所拥有的代码。
@app.route('/apuntual', methods = ['GET','POST'])
def apunt():
if request.method == 'POST':
# This is the button that I click on the video
if request.form.get('capturar') == 'capturar':
sample_rate_unf = request.form.get('f_muestreo')
samples_to_acq_unf = request.form.get('m_canal')
#Changing the values to int so I can work with them
sample_rate = int(sample_rate_unf)
samples_to_acq = int(samples_to_acq_unf)
#lots of more code in here
#
# Sending the output values to make the graph, and some other values to
# display in the html
return render_template('apuntual.html', fmax = fmax, tad = tad, imagen = datos)
<div class="col-md-2">
<form method="POST">
<h5 class="mb-1">Frecuencia de muestreo</h5>
<select name="f_muestreo">
<option value="2048">2048</option>
<option value="2560">2560</option>
<option value="3200">3200</option>
<option value="5120">5120</option>
</select>
<h5 class="mb-1">Muestras por canal</h5>
<select name="m_canal">
<option value="2048">2048</option>
<option value="4096">4096</option>
<option value="8192">8192</option>
</select>
<h5 class="mb-1">Captura instantánea</h5>
<p class="bs-component">
<input type="submit" class="btn btn-primary" name="capturar" value="capturar">
<input type="submit" class="btn btn-primary" name="borrar" value="borrar">
</p>
<p class=""bs-component>Frecuencia máxima de: {{ fmax }} Hz con TAD: {{ tad }} ms.</p>
</form>
</div>
发布于 2021-07-21 10:58:58
我能想到的一种解决方案是将选定的选项作为变量传递给模板,并在模板中标记选定的选项。这是一个演示:
@app.route("/", methods=("GET", "POST"))
def demo():
options = (1, 2, 3, 4)
selected = None
if request.method == "POST":
selected = int(request.form.get("something"))
# Rest of the code goes here
return render_template("demo.html", options=options, selected=selected)
<form method="POST">
<select name="something">
{% for op in options %}
{% if selected == op %}
<option value="{{ op }}" selected>{{ op }}</option>
{% else %}
<option value="{{ op }}">{{ op }}</option>
{% endif %}
{% endfor $}
</select>
<input type="submit">
</form>
请注意,我将所有选项作为元组放在服务器代码中。其中一个原因是为了避免模板代码中的重复。将数据直接存储到前端代码通常也被认为是不好的做法,就像您在这里所做的那样。我的演示也不完美。更好的解决方案是将所有这些选项放入一个配置文件中。
https://stackoverflow.com/questions/68462952
复制相似问题