TurboGears – CRUD Operations


The following session methods perform CRUD Operations −

  • DBSession.add(model object) − inserts a record into mapped table.

  • DBSession.delete(model object) − deletes record from the table.

  • DBSession.query(model).all() − retrieves all the records from table (corresponding to a SELECT query).

You can apply filter to the retrieved record set by using a filter attribute. For instance, in order to retrieve records with city = ’Hyderabad’ in students table, use the following statement −

DBSession.query(model.student).filter_by(city = ’Hyderabad’).all()

We shall now see how to interact with the models through controller URLs.

First let us design a ToscaWidgets form for entering the student’s data


import tw2.core as twc
import tw2.forms as twf

class StudentForm(twf.Form):
   class child(twf.TableLayout):
      name = twf.TextField(size = 20)
      city = twf.TextField()
      address = twf.TextArea("",rows = 5, cols = 30)
      pincode = twf.NumberField()

   action = '/save_record'
   submit = twf.SubmitButton(value = 'Submit')

In the RootController (root.py of Hello application), add the following function mapping ‘/add’ URL −

from hello.controllers.studentform import StudentForm

class RootController(BaseController):
   def add(self, *args, **kw):
      return dict(page='studentform', form = StudentForm)

Save the following HTML code as studentform.html in the templates folder −

<!DOCTYPE html>
<html xmlns = "http://www.w3.org/1999/xhtml"
   xmlns:py = "http://genshi.edgewall.org/"
   lang = "en">
      <title>Student Registration Form</title>
      <div id = "getting_started">
         ${form.display(value = dict(title = 'Enter data'))}


Enter http://localhost:8080/add in the browser after starting the server. The following Student information form will open up in the browser −


The above form is designed to be submitted to the ‘/save_record’ URL. Hence a save_record() function needs to be added in the root.py to expose it. The data from the studentform is received by this function as a dict() object. It is used to add a new record in the student table underlying student model.

#@validate(form = AdmissionForm, error_handler = index1)

def save_record(self, **kw):
   newstudent = student(name = kw['name'],city = kw['city'],
      address = kw['address'], pincode = kw['pincode'])
   flash(message = "new entry added successfully")

Please note that after the successful addition, the browser will be redirected to ‘/listrec’ URL. This URL is exposed by a listrec() function. This function selects all records in the student table and sends them in the form of a dict object to the studentlist.html template. This listrec() function is as follows −

@expose ("hello.templates.studentlist")
def listrec(self):
   entries = DBSession.query(student).all()
   return dict(entries = entries)

The studentlist.html template iterates through the entries dictionary object using py:for directive. The studentlist.html template is as follows −

<html xmlns = "http://www.w3.org/1999/xhtml"
   xmlns:py = "http://genshi.edgewall.org/">
      <link rel = "stylesheet" type = "text/css" media = "screen" 
         href = "${tg.url('/css/style.css')}" />
      <title>Welcome to TurboGears</title>
      <h1>Welcome to TurboGears</h1>
      <py:with vars = "flash = tg.flash_obj.render('flash', use_js = False)">
         <div py:if = "flash" py:replace = "Markup(flash)" />
      <h2>Current Entries</h2>
      <table border = '1'>
            <py:for each = "entry in entries">

Now revisit the http://localhost:8080/add and enter data in the form. By clicking on the submit button, it will take the browser to studentlist.html. It will also flash a ‘new record added successfully’ message.