TurboGears, Tableform and a callable option to a Widget
Wednesday, June 10th, 2009While doing some TurboGears development I ran into an issue where I needed to generate a select field’s options from the database that was dependent on authentication. Since defining the query in the model results in a cached result when the class is instantiated, the query couldn’t be defined there. There are multiple mentions of using a callable to deal with this situation, but, no code example.
From this posting in Google Groups for TurboGears, we were able to figure out the code that made this work.
template:
<div xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/" xmlns:xi="http://www.w3.org/2001/XInclude" py:strip=""> ${tmpl_context.form(value=value)} </div>
controller:
@expose('cp.templates.template') def form(self): c.form = TestForm() c.availips = [[3,3],[2,2]] return dict(template='form',title='Test Form',value=None)
model:
from pylons import c def get_ips(): return c.availips class TestForm(TableForm): action = '/test/testadd' submit_text = 'Add test' class fields(WidgetsList): User = TextField(label_text='FTP Username', size=40, validator=NotEmpty()) Password = PasswordField(label_text='FTP Password', size=40, validator=NotEmpty()) ip = SingleSelectField(label_text="Assign to IP",options=get_ips)