问题
i am trying to create sign up form using flask-wtf, and wtforms-alchemy on this form i try create selectfield, which the value is query from my models. but i'am always get this error:
ValueError: too many values to unpack (expected 2)
this my code:
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)
and this my 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 %}
my package versions is flask-wtf==0.14.2 and wtforms-alchemy==0.16.7
i have try to follow this Why does Flask WTForms and WTForms-SQLAlchemy QuerySelectField produce too many values to unpack? , but i am still confused how to do that.
回答1:
You can define a function as following which can be passed as a get_pk paramater.
def get_pk(obj):
return str(obj)
and then do the following change
domicile = QuerySelectField(u'Domicile', query_factory=choose_domicile, get_pk=get_pk)
I am assuming that you have define __str__
in model class else return pk in get_pk
来源:https://stackoverflow.com/questions/51914900/flask-wtforms-alchemy-queryselectfield-valueerror-too-many-values-to-unpack-ex