我有一个非常基本的Flask应用程序:
from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms_sqlalchemy.fields import QuerySelectField
from wtforms.validators import DataRequired
from flask_sqlalchemy import SQLAlchemy
from wtforms import StringField
db = SQLAlchemy()
app = Flask(__name__)
app.config['SQLALCHEMY_URI'] = 'sqlite:///:memory:'
app.config['SECRET_KEY'] = 'fnord'
db.init_app(app)
class Section(db.Model):
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.Text, nullable = False)
subject_id = db.Column(db.Integer, db.ForeignKey('subject.id'))
subject = db.relationship('Subject', back_populates='sections')
class Subject(db.Model):
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.Text, nullable = False)
sections = db.relationship('Section', back_populates='subject')
def do_something():
return Subject.query
class SelectionForm(FlaskForm):
name = StringField('Section Name', validators=[DataRequired()])
subject = QuerySelectField('Subject', query_factory=do_something, allow_blank=False, get_label='name')
with app.app_context():
db.create_all()
db.session.add(Subject(id=1, name='Science'))
db.session.add(Subject(id=2, name='Math'))
db.session.commit()
@app.route('/')
def main():
form = SelectionForm()
return render_template('index.html', form=SelectionForm())
app.run('0.0.0.0', port=5000, debug=True)
使用非常简单的模板:
<!DOCTYPE html>
<html>
<body>
{{ form.csrf_token }}
{{ form.name }}
{{ form.subject }}
</body>
</html>
问题在于我得到ValueError: too many values to unpack (expected 2)
。这显然不是我所期望的 - 据我所知,我可以跟随我在网上看过的例子,但这里有些不同。问题是,无论wtforms_sqlalchemy / fields.py文件中发生了什么,它都会得到(<class '__main__.Subject'>, (1), None)
,而不是我预期的可能是其他东西,因为它&#39;尝试分配给cls, key
,可能是(<class '__main__.Subject'>, 1)
。
那我在这里做错了什么?
答案 0 :(得分:2)
基于pjcunningham链接的补丁,因为wtforms尚未发布该更新,我继续创建自己的monkeypatch:
import wtforms_sqlalchemy.fields as f
def get_pk_from_identity(obj):
cls, key = f.identity_key(instance=obj)[:2]
return ':'.join(f.text_type(x) for x in key)
f.get_pk_from_identity = get_pk_from_identity
在我的代码库中填充它已经足够现在可以工作,直到他们删除了与最新版本的SQLAlchemy一起使用的版本。