librelist archives

« back to archive

QuerySelectField question

QuerySelectField question

From:
Charles Griebel
Date:
2012-06-07 @ 16:00
[tl;dr - sorry]
I am a flask newbie using the sqlalchemy extension and I have a
question about foreign keys and forms and the use of
wtf.QuerySelectField. When I go to collect the form data from a POST
the wtf.QuerySelectField is an object so when I persist a new record
in the db. I have to use form.device_id.data.id instead of
form.device_id.data. That works. I see in the wtf documentation for
wtf.QuerySelectField (ext.html#module-wtforms.ext.sqlalchemy) that
"The data property actually will store/keep an ORM model instance, not
the ID." So that correlates with what I'm seeing.

I use wtfQuerySelectField in a wtf form like so:

def device_query():
...return Device.query.all()

class MaintWindowForm(wtf.Form):
...device_id = wtf.QuerySelectField(query_factory=device_query,
........get_label='name', allow_blank=False)
<...>

I my app. I have a function to edit the existing record which, when it
initially loads the form, did not properly set the "selected" property
of the device_id in the html option field. In other words, when I was
editing the record the option pulldown was not correctly set to the
current value as a default. To get it to work I edited
/WTForms-1.0.1-py2.7.egg/wtforms/ext/sqlalchemy/fields.py
and changed the yield in the iter_choices method in QuerySelectField
class to hack in a comparison to the "id" column (primary key) like
so:

#yield (pk, self.get_label(obj), obj == self.data)
yield (pk, self.get_label(obj), obj == self.data or obj.id == self.data)

This correctly yields True in the third field of the yielded tuple
and, thus, sets the "selected" property to the html option that is
currently set in the sqlite3 db. The fact that I had to hack this in
makes makes me wonder if I'm just doing it all wrong. I hope I'm being
clear enough.

Thanks

Chock