python - 如何使用 Flask-WTF 在 Python Flask Dynamic SelectField 中添加“无”值?
问题描述
我在 Flask 中创建了一个简单的项目,我想在我的下拉列表中添加 None 值这是我创建表单并将其命名为MovementForm
我的 forms.py 文件中的代码
class MovementForm(FlaskForm):
to_location = SelectField('To Location', choices=[])
from_location = SelectField('From Location', choices=[])
add_movement = SubmitField('Add Movement')
这是我添加运动的路线
@app.route('/movements',methods=["GET","POST"])
def add_movements():
form = MovementForm()
form.to_location.choices = [(location.id, location.location_name) for location in Location.query.all()]
form.from_location.choices = [(location.id, location.location_name) for location in Location.query.all()]
return render_template('add_movements.html')
这是HTML文件
{%extends 'layout.html'%}
{% block content %}
<div class="container">
<h2 class="text-center mt-3">
Movements
</h2>
<form action="/movements" method="post">
{{ form.csrf_token }}
<div class="row">
<div class="form-group col">
{{ form.from_location.label(class="form-control-label") }}
{{ form.from_location(class="form-control form-control-lg") }}
</div>
<div class="form-group col">
{{ form.to_location.label(class="form-control-label") }}
{{ form.to_location(class="form-control form-control-lg") }}
</div>
</div>
<input type="submit" value="Add movement" class="form-control btn btn-primary">
</form>
{% endblock %}
我尝试将“无”附加到选项中,但它引发了错误,我该如何完成?
解决方案
你得到什么样的错误?你能把它添加到问题中吗?
此外,如果您将其更改为 FlaskForm 烧瓶,这是否可以解决问题:
class MovementForm(FlaskForm):
to_location = SelectField('To Location', coerce=int)
from_location = SelectField('From Location', coerce=int)
add_movement = SubmitField('Add movement')
基本上因为您使用的是动态选择字段,您应该添加“coerce=int”而不是choices=[]
另外,您如何添加“无”字段?你想达到什么目的?
编辑
我尝试像这样添加一个“无”选择字段:
@app.route('/movements',methods=["GET","POST"])
def add_movements():
form = MovementForm()
form.to_location.choices = [(location.id, location.location_name) for
location in Location.query.all()]
form.from_location.choices = [(location.id, location.location_name) for
location in Location.query.all()]
// Adding the None in the choices select field in Index 0
form.to_location.choices.insert(0, (0, 'None'))
form.from_location.choices.insert(0, (0, 'None'))
return render_template('add_movements.html')
推荐阅读
- javascript - 分层布局中节点的位置以构建类似图表的“逻辑门”
- javascript - Selenium webdriver:firefox无头注入javascript来修改浏览器属性
- unity3d - 下一个附加之前的统一点延迟不起作用
- php - 即使在给定表中保存数据后,PostgreSQL 也会返回 42P01
- r - 根据另一列中的常见值聚合 R 中列值的所有可能组合
- c++ - 对象创建必须使用哪种设计模式?
- r - 如何选择具有相同数字绝对值的行
- dataset - 报表服务器 2016 无法从共享数据集中加载数据
- reactjs - 用 Jest 反应单元测试 - 模拟 localStorage 的问题
- java - 如何在此应用程序中添加在前台花费的总时间而不是上次使用的时间?