I'm coming to TG from ASP.NET, which means I love Data Binding, and I
know Python/TG would make binding a dropdown/combo list to a dynamic
set of data really easy, but I'm struggling in figuring it out.
Assuming I have a State model defined with abbreviation and name
fields, how would I build a US states drop down list? Following the
Toolbox SingleSelectField widget example, I've experimentally tried:
states = State.select()
list = widgets.SingleSelectField(options=states)
but apparently either SQLObject isn't a list or select's result isn't
a tuple:
File "c:\python24\lib\site-packages\TurboGears-1.0.3.2-py2.4.egg
\turbogears\wi
dgets\forms.py", line 882, in _extend_options
if (len(opts) > 0) and not isinstance(opts[0], (tuple,list)):
TypeError: len() of unsized object
I know I could iterate over states myself and build a tuple of lists,
but I'm lazy -- is there a way to tell SingleSelectField "for each
object, use these results and use this property as your value and this
property as your text"?
I would use the SQL Construction Language instead of the ORM:
state_list = select([state_table.c.abbrev,state_table.c.name],
order_by=[state_table.c.abbrev]).execute()
state = widgets.SingleSelectField(options=state_list)
This syntax seems to have changed a bit in 0.4 though...
Steve
No. And it's so trivial, that you can write it in a split-second
yourself, tailored to specific needs:
def prop_list(objects, attribute, sorted=True):
res = [(o.id, getattr(o, attribute)) for o in objects]
if sorted:
if not callable(sorted):
sorted = lambda v: v[1]
res.sort(key=sorted)
return res
Diez