Why does Flask WTForms and WTForms-SQLAlchemy Quer

2019-01-15 17:37发布

问题:

I've got a pretty basic Flask app:

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)

With a very simple template:

<!DOCTYPE html>
<html>
  <body>
    {{ form.csrf_token }}
    {{ form.name }}
    {{ form.subject }}
  </body>
</html>

The problem with this is that I get ValueError: too many values to unpack (expected 2). This is obviously not what I expected - as far as I can tell I'm following the examples that I've seen online, but something is different here. The problem is that whatever is going on under the hood in the wtforms_sqlalchemy/fields.py file, it's getting (<class '__main__.Subject'>, (1), None), instead of what I would have expected to probably be something else, since it's trying to assign to cls, key, probably (<class '__main__.Subject'>, 1).

So what am I doing wrong here?

回答1:

Based on the patch that pjcunningham linked to, since wtforms hasn't released that update yet, I went ahead and created my own 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

Plopping that in my codebase is enough to work for now until they cut a release that works with the newest version of SQLAlchemy.