I am trying to generate a drop down list of all the users in my database so I can assign admins later that can edit their information. I keep getting the following error from my template:
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 %}
More of the error readback
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))
I’m still new to this so please go easy on me.
Advertisement
Answer
Hope this helps.
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)