使用Flask Python加载选择字段

时间:2019-02-16 20:47:07

标签: python flask flask-wtforms wtforms

所以我正在尝试在网页上加载SelectField。 当我使用浏览器在localhost上连接时,烧瓶崩溃。 显示以下消息:“ *调试器PIN:320-071-095”

from flask import Flask, render_template, request
from flask_wtf import FlaskForm
from wtforms import SelectField, RadioField

from main import mut_infos, year_infos

app = Flask(__name__)
app.config['SECRET_KEY'] = "BoomVroom"



class SelYear(FlaskForm):
    years = SelectField(u'year', choices= list(year_infos.keys()),coerce=int)

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

years_infos是一个以整数为键的字典。

这是index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Flask WebApp</title>
</head>
<body>
    <form method="POST" action="{{ url_for('index') }}">
        {{ form.csrf_token }}
        {{ form.years }}
    </form>

</body>
</html>

修改: 在终端上

 * Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 320-071-095

在网页上,它只是说找不到服务器 “嗯。我们找不到该站点。”

1 个答案:

答案 0 :(得分:0)

我认为您必须重新选择清单。在文档中可以找到,SelectField需要一个元组列表:https://wtforms.readthedocs.io/en/stable/fields.html

choices = [('cpp','C ++'),('py','Python'),('text','Plain Text')]

您可以做的是这样的:

def choicelist():
    choices = []
    for c in choices # refer to your list of years here
        choices.append((str(c), c)) 

    return choices

并将您的choices = list(year_infos.keys())指向该choicelist函数。