pythonturbogears2toscawidgets

How to set the default option value in SingleSelectField?


I'm new to Turbogears 2.3.3 and Toscawidgets 2. Could anyone tell me how to set the default value based on the id?

URL: .../view?id=2

FormWidget:

FruitForm(twf.Form):  
    class child(twf.TableLayout):  
        fruit=twf.SingleSelectField(options=DBsession.query(Fruit.id, Fruit.name)  

Model: Fruit
id, name

Controller:

@expose ('view')  
def view(self, id)  
    fruit=DBSession.query(Fruit).get(id)  
    return dict(page='view', value=fruit, form=FruitForm(action='/save')  

Template:

<div>${form.display(value=value)}</div>  

Question:
When the url is /view?id=2, in the SingleSelectField how to display the fruit whose id is 2?

Thanks.


Solution

  • There are probably two errors in your snippet:

    The first is that options are loaded without using Deferred which causes the query to be executed on application startup (when the form is imported) and not when the form is displayed which is probably not what you want.

    The second is that you are setting as form value the fruit itself, while the value in case of a form should be a dictionary of the children values (as form actually have multiple values, one for each child).

    I created a short example on Runnable of a possible working solution: http://runnable.com/U-tO4xSN7Ch6wWS7/turbogears-forms-fill-singleselect-value-for-pythonpos