Search code examples
formspython-2.7turbogears2

Turbogears Toscawidget not working


I searched in this guide and this guide, and I followed the examples. This is my controller in controllers/root.py:

@expose('rubrica.templates.submitForm')
def add(self, *args, **kw):  
    return dict(page='submitForm', form=SubmitForm)

@expose()
def save_record(self, **kw):
    print('save_record')
    new_contact = Contact(name = kw['name'], phone = kw['phone'])
    model.DBSession.add(new_contact)
    flash(message = "Added new contact")
    redirect('/index')

this is SubmitForm.py:

import tw2.core as twc
import tw2.forms as twf
class SubmitForm(twf.Form):
    class child(twf.TableLayout):
        name = twf.TextField(size = 20)
        phone = twf.TextField(size = 20)
        action = '/save_record'
        submit = twf.SubmitButton(value = 'Submit')

and this is the template:

<head py:block="head" py:strip="True">
    <title py:block="master_title">Aggiungi Contatto</title>
</head>
<body py:block="body" py:strip="True">
    <div>
        ${form.display(value = dict(title = 'Inserisci i dati'))}
    </div>
</body>
</html>

The problem is that save_record is not called(action = '/save_record' should call it, but nothing happens) I can't figure out why.. guess I did something wrong, or something is missing but I can't get it :)

Thanks for help!


Solution

  • action and submit are properties of the Form, but you are specifying them in the Layout. Move the action and submit properties out in the parent scope and it should work as you expect:

    import tw2.core as twc
    import tw2.forms as twf
    
    class SubmitForm(twf.Form):
        class child(twf.TableLayout):
            name = twf.TextField(size = 20)
            phone = twf.TextField(size = 20)
    
        action = '/save_record'
        submit = twf.SubmitButton(value = 'Submit')