If you benefit from web2py hope you feel encouraged to pay it forward by contributing back to society in whatever form you choose!

Below are two tables that have a one to many relationship:

  contact= db.define_table('contacts',
    Field('name'),Field('email')
  )

  groups = db.define_table('groups',
    Field('contact',contacts, readable=False,writable=False),
    Field('group')
  )

For entering data using two data models, is used SQLFORM.factory:

def new():
    form = SQLFORM.factory(db.contact,db.groups)

    if form.accepts(request.vars):
        _id_user = db.contacts.insert(**db.contacts._filter_fields(form.vars))

        form.vars.contact = _id_user

        id = db.groups.insert(**db.groups._filter_fields(form.vars))

        response.flash = 'User registered successfully'
    return locals()

Now, after sending the record ID for the action of editing, we will prepare the data and prepare the update:

def update():
    id = request.args(0)

    group = db(db.groups.id == id).select()[0]

    form = SQLFORM(db.contacts, group.contact.id)
    group = SQLFORM(db.group, group.id)

    # Adding the group form
    form.append(group)

    if form.accepts(request.vars):

        # Updating the contacts
        db.contacts.update(**db.contacts._filter_fields(form.vars))

        # Atualizando o grupo
        old_group = db(db.groups.id == group.id).select().first()
        old_group.update_record(group=group.vars.group)

        response.session = 'Updated with success!'

    return locals()

Ideas and improvements are welcome!

Bye!

Related slices

Comments (0)


Hosting graciously provided by:
Python Anywhere