如何使用FlaskWTF在Python Flask Dynamic SelectField中添加“None”值?

2024-09-30 06:18:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Flask中创建了一个简单的项目,我不想在下拉列表中添加任何值 下面是一段if代码,我在其中创建了表单,并在forms.py文件中将其命名为MovementForm

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 %}

我试着在选项后面加上“无”,但它抛出了一个错误,我如何才能做到这一点


Tags: 文件tofromdivformaddlocationlabel
1条回答
网友
1楼 · 发布于 2024-09-30 06:18:46

你会犯什么样的错误?你能把它加到问题上吗

此外,如果您将其更改为烧瓶形式烧瓶,这是否可以解决问题:

class MovementForm(FlaskForm):
    to_location = SelectField('To Location', coerce=int)
    from_location = SelectField('From Location', coerce=int)
    add_movement = SubmitField('Add movement')

基本上,因为您使用的是动态选择字段,所以应该添加“强制=int”,而不是选择=[]

另外,如何添加“无”字段? 你想达到什么目标


EDIT

我尝试添加一个“无”选择字段,如下所示:

@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')

相关问题 更多 >

    热门问题