使用 Flask Python 加载 Select 字段

Load Select Field with Flask Python

所以我正在尝试在网页上加载 SelectField。 当我使用浏览器连接本地主机时 Flask 崩溃。 带有此消息:“* 调试器 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

网页上说找不到服务器 "Hmm. We’re having trouble finding that site."

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

选择=[('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()) 指向该选择列表函数。