flask wtforms-alchemy QuerySelectField ValueError:太多值无法解包(预期2)

时间:2018-08-19 05:56:36

标签: python flask sqlalchemy flask-sqlalchemy flask-wtforms

我正在尝试使用 flask-wtf wtforms-alchemy 创建注册表单 在此表单上,我尝试创建selectfield,该值是从我的模型中查询的。 但我总是会收到此错误:

 ValueError: too many values to unpack (expected 2)

这是我的代码

from flask_wtf import FlaskForm
from wtforms_sqlalchemy.fields import QuerySelectField

def choose_domicile():
    return Domicile.query

class RegisterForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()])
    domicile = QuerySelectField(u'Domicile', query_factory=choose_domicile)


@app.route('/signup', methods=['GET', 'POST'])
    def signup():
        form = RegisterFormView()
        try:
            if form.validate_on_submit():
                new_user = Data(name=form.name.data, domicile=form.domicile.data)
                db.session.add(new_user)
                db.session.commit()
                return "Success"
        except:
            return "Failed"

        return render_template('signup.html', form=form)

这是我的 signup.html

{% block content %}
<div class="container">

  <form class="form-signin" method="POST" action="/signup">
    <h2 class="form-signin-heading">Sign Up</h2>
    {{ form.hidden_tag() }}
    {{ wtf.form_field(form.name) }}
    {{ form.domicile }}
    <button class="btn btn-lg btn-primary btn-block" type="submit">Sign Up</button>
  </form>

</div>
{% endblock %}

我的软件包版本为 flask-wtf == 0.14.2 wtforms-alchemy == 0.16.7

我尝试遵循此Why does Flask WTForms and WTForms-SQLAlchemy QuerySelectField produce too many values to unpack?,但是我仍然对如何做到这一点感到困惑。

1 个答案:

答案 0 :(得分:2)

您可以定义以下函数,并将其作为get_pk参数传递。

def get_pk(obj):
    return str(obj)

然后进行以下更改

domicile = QuerySelectField(u'Domicile', query_factory=choose_domicile, get_pk=get_pk)

我假设您已经在模型类中定义了__str__,否则在get_pk中返回pk