Pyramid framework tips: Form validation

For form validation in pyramid framework there is FormEncode package. FormEncode is a validation and form generation package. pyramid_simpleform is a add-on for pyramid framework and uses FormEncode.

SimpleForm in Pyramid Applications: install with easy_install:

$ easy_install pyramid_simpleform

In your controller code FormEncode Schema:

class CategoryForm(Schema):
  filter_extra_fields = True
  allow_extra_fields = True
  # category name not empty
  name = validators.String(not_empty=True)

 # edit function with form.validate()
 @view_config(route_name="category_edit", renderer="category/edit.html")
 def edit(request):
    """category edit """
    id = request.matchdict['id']
    dbsession = DBSession()
    category = dbsession.query(Category).filter_by(id=id).one()
    if category is None:
        request.session.flash("error;Category not found!")
        return HTTPFound(location=request.route_url("category_list"))        

    form = Form(request, schema=CategoryForm, obj=category)
    if "form_submitted" in request.POST and form.validate():
        request.session.flash("warning;The Category is saved!")
        return HTTPFound(location = request.route_url("category_list"))

    action_url = request.route_url("category_edit", id=id)
    return dict(form=FormRenderer(form),

See please full customers app code for template details.

Pyramid framework tips : Mako Templates settings

mako templates pyramid framework

In Pyramid framework you can use the mako templates.

In development.ini and production.ini:

# mako template settings
mako.directories = YOUR_PROJECT_NAME:templates

It is better to save your mako files with *.html if you use html editors or Eclipse / Aptana.
For *.html you must add pyramid mako renderer factory in Pyramid Application in

def main(global_config, **settings):
  """ This function returns a Pyramid WSGI application.
  # mako settings for file extension .html
  config.add_renderer(".html", "pyramid.mako_templating.renderer_factory")

If you are not adding mako templating renderer factory, you get this error:
ValueError: No such renderer factory .html