Mojo offers convenience functions to make handling forms with the database easier. At it’s core these functions are wrappers arounf basic wtForms functionality to make Form management easier.
A wrapper around the standard wtForms Form object that integrates with tornado. Modified slightly for compatibility with Mojo models - you can pre-populate a form and populate a model using this Form class instead of the standard wtForms Form.
Example:
class SigninForm(Form):
email = EmailField('email')
password = PasswordField('password')
class SigninHandler(RequestHandler):
def get(self):
form = SigninForm(self.request.arguments, locale_code=self.locale.code)
Populates a form from a model, if you want to ignore some fields, use the ignore list (of strings) to set which fields not to be iterated over.
Will populate a model from the data provided by a form. Use the ignore list (must all be strings) to ignore data keys passed back by your form.
Will take a model (non instantiated) object and produce a WTForm Form instance, this function only works one-way.
model_as_form can take three parameters:
as part of the override, simply specify them in the override as if you would in a standard Form definition.
Usage:
from Mojo.Forms.MojoFormHelper import model_as_form
# Let's get some data from our imaginary blog app
posts = yield gen.Task(BlogPost.find_async, {'published':True}, sort=[('date_published',1)])
a_post = posts[0]
# Define a custom override set, the first is a base class,
# the second is an instance with my custom validators:
overrides = {'post_body': TextAreaField,
'post_intro': TextAreaField('Your intro text', [validators.required(),
validators.length(max=10)]}
# Create the form - we will ignore tags and
# comments (these are Lists, and not implemented),
# and override with our custom fields (StringFields are by
# default TextFields, but we want TextAreas):
thisForm = model_as_form(BlogPost, initObj=a_post, ignore=['tags', 'comments'], override=overrides)
# ...Now do something with the form
The system will automatically transform required model fields to required Form fields, no other validation checks are passed through yet.
For the ‘friendly name’ o your form field, Mojo will use the friendly Mojo Model Form parameter, if none is present, Mojo will use the name of the Modle Field.