我正在尝试生成数据库中所有用户的下拉列表,以便稍后可以指定可以编辑其信息的管理员。我不断从模板中收到以下错误:
AttributeError: 'QueryAllUsers' object has no attribute '_fields'
views.py
@app.route('/mobility_add_users', methods=['GET', 'POST'])
@login_required
def mobility_add_users():
#users=User.query.all()
form=QueryAllUsers(request.form)
return render_template('mobility_add_users.html',title='Mobility Add Users', form=form)
forms.py
class QueryAllUsers(Form):
print("In QueryAll")
#users=User.query.all()
user_list = SelectField(u'Choose')
def __init__(self, *args, **kwargs):
self.user_list.choices=[(obj.id, obj.username) for obj in User.query.order_by('username')]
print("Query all done")
models.py
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(32), index=True, unique=True)
password_hash = db.Column(db.String(128))
email = db.Column(db.String(120), index=True, unique=True)
posts = db.relationship('Post', backref='author', lazy='dynamic')
#mobilitys = db.relationship('Mobility', backref='username', lazy='dynamic')
about_me = db.Column(db.String(140))
last_seen = db.Column(db.DateTime)
mobility_add_users.html
<!-- extend base layout -->
{% extends "base.html" %}
{% block content %}
{% from "_formhelpers.html" import render_field %}
<form method=post>
<dl>
{{ form.hidden_tag() }}
{{ render_field(form.query) }}
</dl>
<p><input type=submit value=Register></p>
</form>
{% endblock %}
更多错误回读
File "/home/jsnyder10/Documents/45/app/templates/mobility_add_users.html", line 8, in block "content"
{{ form.hidden_tag() }}
File "/home/jsnyder10/Documents/45/flask/lib/python2.7/site-packages/flask_wtf/form.py", line 135, in hidden_tag
u'\n'.join(text_type(f) for f in hidden_fields(fields or self))
File "/home/jsnyder10/Documents/45/flask/lib/python2.7/site-packages/flask_wtf/form.py", line 135, in <genexpr>
u'\n'.join(text_type(f) for f in hidden_fields(fields or self))
File "/home/jsnyder10/Documents/45/flask/lib/python2.7/site-packages/flask_wtf/form.py", line 125, in hidden_fields
for f in fields:
File "/home/jsnyder10/Documents/45/flask/lib/python2.7/site-packages/wtforms/form.py", line 57, in __iter__
return iter(itervalues(self._fields))
我还是新手,所以请放轻松我。
答案 0 :(得分:1)
表单未在您的视图中正确初始化,应为:
@app.route('/mobility_add_users', methods=['GET', 'POST'])
@login_required
def mobility_add_users():
#users=User.query.all()
form=QueryAllUsers(request.form)
return render_template('mobility_add_users.html',title='Mobility Add Users', form=form)
请参阅wtforms doc。
答案 1 :(得分:1)
希望这有帮助。
from wtforms.ext.sqlalchemy.fields import QuerySelectField
class QueryAllUsers(Form):
user_list = QuerySelectField(
'Choose',
query_factory=lambda: User.query, // you can add order_by(I am not sure)
allow_blank=False
)
class User(db.Model):
// add below lines to your model. you can refactor this as per your need.
def __repr__(self):
return "<User(id='%s', name='%s')>" % (self.id, self.name)