首页 > 解决方案 > 如何使用 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 %}

我尝试将“无”附加到选项中,但它引发了错误,我该如何完成?

标签: pythonflaskflask-wtforms

解决方案


你得到什么样的错误?你能把它添加到问题中吗?

此外,如果您将其更改为 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')


推荐阅读