【问题标题】:Load Select Field with Flask Python使用 Flask Python 加载选择字段
【发布时间】:2019-02-16 20:47:07
【问题描述】:

所以我正在尝试在网页上加载 SelectField。 当我使用浏览器在 localhost 上连接时,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

在网页上,它只是说找不到服务器 “嗯。我们很难找到那个网站。”

【问题讨论】:

  • 我几乎可以肯定调试器提供的反馈不仅仅是密码?请发布完整的错误记录。
  • 我已经编辑了帖子。
  • 嗯,这不是崩溃,没关系。您在浏览器中使用什么来打开您的应用程序?它应该是地址栏中的“127.0.0.1:5000”或“localhost:5000”,然后按回车...
  • 是的,这就是我正在做的。它适用于其他页面,并且在页面为空白时工作正常。但是当我在 render_template 中添加上下文时,它找不到服务器。更准确地说,服务器结束,终端“还手”(对不起,不是英语本地人)。
  • 你能告诉我们这是什么输出吗:choices= list(year_infos.keys())。

标签: python flask flask-wtforms wtforms


【解决方案1】:

我认为你必须重新审视你的选择列表。可以在文档中找到,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 函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多