Speed up development with full-stack environments for every branch.

Learn More

Automatic Forms generation with Sprox and SQLAlchemy [Python and TurboGears]

Forked from Setting up SQLAlchemy in TurboGears minimal mode [Python].

83 Runs 210 Views 19 Copies

Shows how to generate form for a model instead of manually declaring a ToscaWidgets form

Saved

Saved

amol 16

amol
published 3 years ago

import sys
from tg import TGController, AppConfig, expose, validate, redirect
from datetime import datetime
from .model import DBSession, SomeModel
from formencode import validators
from sprox.formbase import AddRecordForm


class AddSomeModelForm(AddRecordForm):
    __model__ = SomeModel
    __omit_fields__ = ['uid']
    __field_validators__ = {'name': validators.String(not_empty=True),
                            'value': validators.Int(not_empty=True)}
add_somemodel_form = AddSomeModelForm(session=DBSession)


class RootController(TGController):
  @expose('sampleapp.index')
  def index(self, **kw):
    entries = DBSession.query(SomeModel).all()
    return dict(entries=entries, form=add_somemodel_form)

  @expose()
  @validate(add_somemodel_form, error_handler=index)
  def make_entry(self, name, value, **kwargs):
    DBSession.add(SomeModel(name=name, value=value))
    return redirect('/')
  
config = AppConfig(minimal=True, root_controller=RootController())

# Models and DB configuration requires a pckage with a *model* module inside
config.package = sys.modules[__package__]

# As we are going to use a package, dotted templates support is better suited
config.use_dotted_templatenames = True
config.renderers = ['genshi']

config.use_toscawidgets2 = True
config.use_sqlalchemy = True
config.use_transaction_manager = True
config.DBSession = DBSession
config['sqlalchemy.url'] = 'sqlite:////tmp/test.db'


application = config.make_wsgi_app()
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).