如何在Flask中呈现Select字段给错误两个多值来解包?

2024-10-03 17:25:40 发布

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

应用程序代码:用于制作表单

branch_choices = [('CSE','CSE'),('ECE','ECE'),('MEC','MEC'),('CIVIL','CIVIL')]
year_choices = [('1st','1st'),('2nd','2nd'),('3rd','3rd'),('4th','4th')]

class CSIForm(Form):
    branch = SelectField('Branch',choices=branch_choices, validators=[Required()])
    year = SelectField('Year',choices=year_choices, validators=[Required()])

def index():
    form=CSIForm()
    return render_template('form.html',form=form)

HTML代码:用于将代码呈现为HTML

^{pr2}$

Tags: 代码formbranchhtmlrequiredyear程序代码choices
2条回答

matthewh提供的代码是正确的-如果您没有在调试模式下运行并且没有重新启动应用程序,那么您可能看不到您的更改。在

下面是一个完整的应用程序,使用matthewh提供的代码:

from flask import Flask, render_template
from flask.ext.wtf import Form
from wtforms import SelectField
from wtforms.validators import Required


branch_choices = [('CSE','CSE'),('ECE','ECE'),('MEC','MEC'),('CIVIL','CIVIL')]
year_choices = [('1st','1st'),('2nd','2nd'),('3rd','3rd'),('4th','4th')]

class CSIForm(Form):
    branch = SelectField('Branch',choices=branch_choices, validators=[Required()])
    year = SelectField('Year',choices=year_choices, validators=[Required()])

app = Flask(__name__)
app.secret_key = "Moo."

@app.route('/')
def index():
    form=CSIForm()
    return render_template('form.html',form=form)


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

呈现页面的源代码是:

^{pr2}$

choices需要是元组的列表,而不是字符串的列表。在

请参阅文档:http://wtforms.readthedocs.org/en/latest/fields.html#wtforms.fields.SelectField

您的代码可以这样更新:

class CSIForm(Form):
    branch_choices = [('CSE','CSE'),('ECE','ECE'),('MEC','MEC'),('CIVIL','CIVIL')]
    year_choices = [('1st','1st'),('2nd','2nd'),('3rd','3rd'),('4th','4th')]
    branch = SelectField('Branch',choices=branch_choices, validators=[Required()])
    year = SelectField('Year',choices=year_choices, validators=[Required()])

相关问题 更多 >